0

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

Munish Kapoor
  • 3,141
  • 2
  • 26
  • 41

4 Answers4

2

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?

Barmar
  • 741,623
  • 53
  • 500
  • 612
0
let filteredFriends = users.filter(user => {
    return this.isUserExist(user);
});
Sascha
  • 4,576
  • 3
  • 13
  • 34
0

Simply do this:

const users = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
let filteredFriends = users.filter(user => this.isUserExist(user));
console.log(filteredFriends);
Jawad
  • 190
  • 10
0

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);
Siva K V
  • 10,561
  • 2
  • 16
  • 29