Filtering array so it would remove all undefined objects

Viewed 2131

I need to filter an array so it would remove undefined objects from it.

enter image description here

I tried with lodash _.filter but didn't succeed (returned completely empty array)

_.filter(myArray, _.isEmpty)

I'm using Angular 6 so anything with typescript or lodash would be perfect.

6 Answers

An easier way:

_.filter(myArray, Boolean)

This rids the array of nulls, 0's and undefined's.

Using Javascript also feasible. it supports null,undefined, 0, empty.

newArray = myArray.filter(item=> item);

The more simple way

_.filter(myArray, function(o) { return o !== undefined });
var newArray = array.filter(arrayItem => arrayItem)

It will Filtering array so it would remove all undefined objects and assign to new variable called newArray

In filter function of lodash if the callback (you passed as argument) return truthy value that element considered to be retained in resultant array otherwise (in case return falsy) it will not retain that element. Your isEmpty return true if it is Empty and thus the result retains those values (null, undefined, 0, ...). So you can either use

_.filter(myArray, _.negate(_.IsEmpty)) or _.filter(myArray, v => !_.IsEmpty(v))

In the way you are trying

Or, you can directly use _.filter(myArray) but in this case it will not remove empty object or empty array as same like _.filter(myArray, Boolean), passing Boolean is not necessery in case of using lodash

in case you don't want to negate and want a simpler solution for removing all the empty element, then you can use

_.reject(myArray, _.isEmpty)

Related