2

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 6

2

An easier way:

_.filter(myArray, Boolean)

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, since this is the cleanest way I will accept this answer once I can.
2

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

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

Comments

1

The more simple way

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

Comments

1

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

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

Comments

1

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)

Comments

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

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

1 Comment

While this might answer the authors question, it lacks some explaining words and/or links to documentation. Raw code snippets are not very helpful without some phrases around them. You may also find how to write a good answer very helpful. Please edit your answer - From Review

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.