1

I'm having afunction that is merging two arrays like this:

var sorting = data.genre.map((i) => data_info.find((o) => o.id === i));

The problem in this function is if it couldn't find genre in data_info it adds null to the object arra and therefore my function fails.
So the question is: How could I remove in above single line all values that are null?

I get this output from thr line above:

[{"id":1,"category":"Action"},{"id":2,"category":"Adventure"},null]

And need to get this:

[{"id":1,"category":"Action"},{"id":2,"category":"Adventure"}]

I tried to add && data_info(o) !== null to the line above but I get null in the object array anyway.

Filnor
  • 1,253
  • 2
  • 22
  • 27
John
  • 871
  • 1
  • 9
  • 28
  • Add a `filter` to the output of `map`. `data.genre.map((i) => data_info.find((o) => o.id === i)).filter((i) => return i != null );` – gurvinder372 Oct 11 '17 at 07:52
  • The map function applies the operation on each item of the array and returns an array with exactly the same number of elements as in the input array. – ajaysinghdav10d Oct 11 '17 at 07:54
  • Possible duplicate of [How to remove item from array by value?](https://stackoverflow.com/questions/3954438/how-to-remove-item-from-array-by-value) – Nikola Lukic Oct 11 '17 at 08:13

3 Answers3

2

change .map to .filter

var sorting = data.genre.filter((i) => data_info.find((o) => o.id === i) ? true : false);
Karim
  • 7,479
  • 1
  • 18
  • 31
1

You can use filter method by passing a callback provided function.

var sorting = data.genre.map((i) => data_info.find((o) => o.id === i)).filter(function(item){
    return item!=null;
});
Mihai Alexandru-Ionut
  • 41,021
  • 10
  • 77
  • 103
1

You can filter the result of your map function to remove null.

var sorting = data.genre.map((i) => data_info.find((o) => o.id === i)).filter(item => {
   return item !== null;
});

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

Paul Fitzgerald
  • 9,462
  • 3
  • 33
  • 49