I have a problem that I cannot solve and it seems a little strange to me. Having a list of objects foo
, each object having a userId
property, I want to filter the list to remove all items containing such userId
that are in the bar
array.
I used the filter()
and some()
methods, however, they only work when the bar
array has only one element.
Does some()
somehow stop the entire filter from running when it finds the first matching element?
I would be thankful if you could explain to me why this does not work.
Example code:
let foo = [
{
"userId": 1,
},
{
"userId": 2
},
{
"userId": 3
},
{
"userId": 4
}
];
let bar = [1, 2];
console.log(foo.filter(user => bar.some(id => id !== user.userId)));
Run code snippetHide resultsExpand snippet
Expected value:
[
{
"userId": 3
},
{
"userId": 4
}
]
But I got:
[
{
"userId": 1,
},
{
"userId": 2
},
{
"userId": 3
},
{
"userId": 4
}
]
CodePudding user response:
Your condition currently checks if there is at least one item in the bar array which is not the same as the items array you are iterating over. That will be true for all items.
You need to check for the items that exist using some()
and based on that return the inverse value .
let foo = [
{
"userId": 1,
},
{
"userId": 2
},
{
"userId": 3
},
{
"userId": 4
}
];
let bar = [1, 2];
console.log(foo.filter(user => !bar.some(id => id === user.userId)));
CodePudding user response:
you can simply use includes
methods to check this situation.
let foo = [
{
"userId": 1,
},
{
"userId": 2
},
{
"userId": 3
},
{
"userId": 4
}
];
let bar = [1, 2];
// filter out for user IDs not in bar
console.log(foo.filter(user => !bar.includes(user.userId)));
for more information about includes method: MDN
CodePudding user response:
The some()
method tests whether at least one element in the array passes the test.
Explanation of Why some()
is not working here:
[1,2].some(id !== 1)
will return true
because id 2 !== 1
[1,2].some(id !== 2)
will return true
because id 1 !== 2
[1,2].some(id !== 3)
will return true
because id 1 !== 3
[1,2].some(id !== 4)
will return true
because id 1 !== 4