John
John

Reputation: 1751

Javascript remove null from object

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.

Upvotes: 1

Views: 230

Answers (3)

Karim
Karim

Reputation: 8632

change .map to .filter

var sorting = data.genre.filter((i) => data_info.find((o) => o.id === i) ? true : false);

Upvotes: 2

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48367

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

Upvotes: 1

Paul Fitzgerald
Paul Fitzgerald

Reputation: 12129

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.

Upvotes: 1

Related Questions