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.

3
  • Add a filter to the output of map. data.genre.map((i) => data_info.find((o) => o.id === i)).filter((i) => return i != null ); Commented Oct 11, 2017 at 7: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. Commented Oct 11, 2017 at 7:54
  • Possible duplicate of How to remove item from array by value? Commented Oct 11, 2017 at 8:13

3 Answers 3

2

change .map to .filter

var sorting = data.genre.filter((i) => data_info.find((o) => o.id === i) ? true : false);
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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;
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.