I have an array that I’m trying to filter:
const elements = ['apple'];
const objects = [
{ id: 1, fruit:[{"name": "apple" },{"name": "banana" }]},
{ id: 2, fruit:[{"name": "apple" },{"name": "orange" }]},
{ id: 3, fruit:[{"name": "orange" },{"name": "banana" }]},
{ id: 4, fruit:[{"name": "orange" },{"name": "banana" }]}
];
const results = objects.filter(obj => obj.fruit.filter( ele => elements.includes(ele.name)));
console.log(results);
I am getting the output as below but this not what I am expecting:
{id: 1, fruit:[{"name": "apple" },{"name": "banana" }]
{id: 2, fruit:[{"name": "apple" },{"name": "banana" }]
I want the output as below:
{ id: 1, fruit:[{"name": "apple" }]}
{ id: 2, fruit:[{"name": "apple" }]}
2
Answers
You could filter
fruit
and if it has elements take the outer object as result.Your snippet will work if you replace the inner
filter
withsome
:.filter()
will always return a "truthy" result. Even an empty array ([]
) will be seen astrue
. The.some()
method on the other hand will only betrue
if the condition in the loop was met at least once.