Reputation: 3339
I have following script which filter the data using for loop as shown
let i;
const filteredFriends = [];
for (i = 0; i < users.length; i += 1) {
if (this.isUserExist(users[i]) {
filteredFriends.push(users[i]);
}
}
How can i covert it into filter
any idea please
Upvotes: 0
Views: 64
Reputation: 11001
filter
method need to return boolean value. your function this.isUserExist
seems doing that as you have used in if condition.
Use it like.
const filteredFriends = users.filter(this.isUserExist);
Upvotes: 0
Reputation: 198
Simply do this:
const users = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
let filteredFriends = users.filter(user => this.isUserExist(user));
console.log(filteredFriends);
Upvotes: 0
Reputation: 4616
let filteredFriends = users.filter(user => {
return this.isUserExist(user);
});
Upvotes: 0
Reputation: 781068
Simply use the if
condition in the callback function of filter()
. Replace user[i]
with the callback function parameter.
const filteredFriends = users.filter(u => this.isUserExist(u))
Make sure you use an arrow function so that this
will be inherited in the callback function. If you need compatibility with older implementations that don't have arrow functions, see How to access the correct `this` inside a callback?
Upvotes: 2