67

In javascript, I want to remove undefined values, but keep the values 0 and null from an array.

[ 1, 2, 3, undefined, 0, null ]

How can I do it cleanly?

JLavoie
  • 16,678
  • 8
  • 33
  • 39

12 Answers12

116

You can use _.compact(array);

Creates an array with all falsey values removed. The values false, null, 0, "", undefined, and NaN are falsey.

See: https://lodash.com/docs/4.15.0#compact

Max Hudson
  • 9,961
  • 14
  • 57
  • 107
Jaynam
  • 1,395
  • 1
  • 8
  • 2
  • 39
    In that case, your answer is not valid as the question states that nulls need to be kept... – Shadow Sep 16 '16 at 05:09
  • Correct, I pushed an edit to that answer in order to explain it and cite the documentation correctly. The values `false`, `null`, `0`, `""`, `undefined`, and `NaN` are being removed by `_.compact`. – Markus Oct 05 '17 at 07:11
  • 1
    your answer is invalid. like it has been stated, the question explicitly disqualifies your answer. – Osuriel Oct 28 '20 at 23:44
  • This answer is exactly what I'm looking for because google redirects me here, even if I ask a different question. Therefore is this answer at this place simple perfect! –  Nov 04 '20 at 08:10
47

The best way using lodash is _.without

Example:

const newArray = _.without([1,2,3,undefined,0,null], undefined);
Piotr Białek
  • 2,569
  • 1
  • 17
  • 26
15

No need for libraries with modern browsers. filter is built in.

    var arr = [ 1, 2, 3, undefined, 0, null ];
    var updated = arr.filter(function(val){ return val!==undefined; });
    console.log(updated);
epascarello
  • 204,599
  • 20
  • 195
  • 236
  • 1
    This is a good example of when using a framework (that isn't included in the project for other reasons) is superfluous. – Shadow Sep 16 '16 at 05:11
  • Great answer! I do think there are reasons to stick with Lodash rather than polyfills when looking for consistency across a code base - would you agree with that? **NOTE:** I do realize this was added with `ECMA-262`, and that's a pretty old version of the spec, so in practice this is less of a polyfill potentially more of a "standard implementation." – Mike Perrenoud Nov 06 '17 at 12:36
  • More and more developers are moving way from Lodash/underscore. The reason why is browsers now are supporting things natively that they were using the library for. Unless you support IE8, I doubt a polyfill is needed for filter. – epascarello Nov 06 '17 at 14:01
11

With lodash, you can do simply:

var filtered = _.reject(array, _.isUndefined);

If you also want to filter null as well as undefined at some point:

var filtered = _.reject(array, _.isNil);

Ryall
  • 12,010
  • 11
  • 53
  • 77
5

Using lodash, the following remove only undefined values from the array:

var array = [ 1, 2, 3, undefined, 0, null ];

_.filter(array, function(a){ return !_.isUndefined(a) }
--> [ 1, 2, 3, 0, null ]

Or, the following will remove the undefined, 0 and null values:

_.filter(array)
--> [1, 2, 3]

And if you want to remove null and undefined values from the array, but keep the values equal to 0:

_.filter(array, function(a){ return _.isNumber(a) || _.isString(a) }
[ 1, 2, 3, 0 ]
JLavoie
  • 16,678
  • 8
  • 33
  • 39
2

With ES6 Array#filter method

array.filter(item => item !== undefined)
Tolotra Raharison
  • 3,034
  • 1
  • 10
  • 15
1

Vanilla JS solution: By using ===, you can check if the value is actually undefined and not falsy.

Both snippets below will give you an array with [1, 2, 3, 0, null].

Both modify the original array.

// one liner - modifies the array in-place
[ 1, 2, 3, undefined, 0, null ].forEach( function(val, i, arr){
    if(val===undefined){arr.splice(i,1)}; // remove from the array if actually undefined
});

// broken up for clarity - does the same as the above
var myarray = [ 1, 2, 3, undefined, 0, null ];
myarray.forEach( function(val, i, arr){
    if(val===undefined){arr.splice(i,1)};// remove from the array if actually undefined 
});
console.log(myarray );
TimBryanDev
  • 173
  • 1
  • 10
1

You can use lodash to do this, you can use _.omitBy(object, _.isUndefined); https://lodash.com/docs/4.17.15#omitBy
in the place of _.isUndefined you can even use _.isNumber, _.isNull and lot of functions. Go to lodash webside and search "is" in search and you can get the list of functions.

1

Plain ES6:

array.filter(a => a !== undefined)

Siva Tumma
  • 1,695
  • 12
  • 23
0

You can try this one.

var array = [ 1, 2, 3, undefined, 0, null ];
var array2 = [];
for(var i=0; i<array.length; i++){
    if(!(typeof array[i] == 'undefined')){
        array2.push(array[i]);
    }
}
console.log(array2);
Amruth
  • 5,792
  • 2
  • 28
  • 41
0

Filter the given array for elements not equal to undefined.

const initialArray = [ 1, 2, 3, undefined, 0, null ];
const finalArray = initialArray.filter(element => element !== undefined);
-1
const finalArray = initialArray.filter(i => Boolean(i))