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.

raouaoul
  • 681
  • 2
  • 13
  • 33

6 Answers6

2

An easier way:

_.filter(myArray, Boolean)

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

rrd
  • 5,789
  • 3
  • 28
  • 36
2

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

newArray = myArray.filter(item=> item);
Suresh Kumar Ariya
  • 9,516
  • 1
  • 18
  • 27
1

The more simple way

_.filter(myArray, function(o) { return o !== undefined });
Ayush Gupta
  • 8,716
  • 8
  • 59
  • 92
firegloves
  • 5,581
  • 2
  • 29
  • 50
1

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

var filteredArray = myArray.filter(item => item !== undefined);
stone
  • 8,422
  • 5
  • 54
  • 66
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

  • 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](https://stackoverflow.com/help/how-to-answer) very helpful. Please edit your answer - [From Review](https://stackoverflow.com/review/low-quality-posts/21387784) – Nick Nov 12 '18 at 10:25
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)

Koushik Chatterjee
  • 4,106
  • 3
  • 18
  • 32