Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

filter of Filter in javascript array

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" }]}
like image 465
vme Avatar asked Oct 28 '25 20:10

vme


1 Answers

You could filter fruit and if it has elements take the outer object as result.

const
    elements = ['apple'],
    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" }] }],
    results = objects.reduce((r, o) => {
        const fruit = o.fruit.filter(({ name }) => elements.includes(name));
        if (fruit.length) r.push({ ...o, fruit });
        return r;
    }, []);
    
console.log(results);
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 150
Nina Scholz Avatar answered Oct 31 '25 12:10

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!