raouaoul
raouaoul

Reputation: 881

Filtering array so it would remove all undefined objects

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.

Upvotes: 2

Views: 2671

Answers (6)

ishani shah
ishani shah

Reputation: 46

var newArray = array.filter(arrayItem => arrayItem)

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

Upvotes: 1

Koushik Chatterjee
Koushik Chatterjee

Reputation: 4175

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)

Upvotes: 1

stone
stone

Reputation: 8662

You don't need a library; the Javascript array type has a filter method:

var filteredArray = myArray.filter(item => item !== undefined);

Upvotes: 1

Suresh Kumar Ariya
Suresh Kumar Ariya

Reputation: 9764

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

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

Upvotes: 2

firegloves
firegloves

Reputation: 5709

The more simple way

_.filter(myArray, function(o) { return o !== undefined });

Upvotes: 1

rrd
rrd

Reputation: 5957

An easier way:

_.filter(myArray, Boolean)

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

Upvotes: 2

Related Questions