skip to Main Content

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


  1. 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; }
    Login or Signup to reply.
  2. Your snippet will work if you replace the inner filter with some:

    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.some( ele => elements.includes(ele.name)));
    console.log(results);

    .filter() will always return a "truthy" result. Even an empty array ([]) will be seen as true. The .some() method on the other hand will only be true if the condition in the loop was met at least once.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search