Not return anything from filter method?

Viewed 30

I have a list array:

list: [
  {
    id: '3',
    title: 'hi',
  },
  {
    id: '4',
    title: 'there',
  },
],

I'm using a method to do some destructuring and return and new array while looking for an item by id

  return {
    title: section.title,
    list: [
      ...section.list,
      storeSections[i].list.filter((field) => field.id === ownId)[0],
    ],
  };

If it finds it, it will just add it to the new array, for example this object:

  {
    id: '3515',
    title: 'hello',
  },

But if it doesn't, it will add 'undefined' to the new array, because the filter method will return undefined.

Is there a simple way to change this behavior so that the filter method only adds an item to the array if it finds it?

2 Answers

use spread, when the array is empty you will not get the extra entry.

var a = [1,2,3];
var b = [4];
var c = [];

console.log([...a, ...b, ...c])

so

 return {
    title: section.title,
    list: [
      ...section.list,
      ...storeSections[i].list.filter((field) => field.id === ownId),
    ],
  };

One solution I found is to add:

    list: [
      ...section.list,
      storeSections[i].list.filter((field) => field.id === ownId)[0],
    ].filter((item) => item !== undefined),

Anothef filter method to remove the undefined values

Related