172

In certain situations, it may happen that we have undefined or generally falsy values in Array structures. For instance when reading and filling data from some unknown sources like Databases or HTML structures. Like

var data = [42, 21, undefined, 50, 40, undefined, 9]

Since that might cause trouble when looping over such arrays and working on the elements, what is the best practice to remove undefined (falsy values) ?

1

16 Answers 16

262

To use Array.prototype.filter here might be obvious. So to remove only undefined values we could call

var data = [42, 21, undefined, 50, 40, undefined, 9];

data = data.filter(function( element ) {
   return element !== undefined;
});

If we want to filter out all the falsy values (such as 0 or null) we can use return !!element; instead.

But we can do it slighty more elegant, by just passing the Boolean constructor function, respectively the Number constructor function to .filter:

data = data.filter( Number );

That would do the job in this instance, to generally remove any falsy value, we would call

data = data.filter( Boolean );

Since the Boolean() constructor returns true on truthy values and false on any falsy value, this is a very neat option.

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

8 Comments

Just note that filter(Number) will also remove 0.
this will also remove falsey values like false, which may exist in the array
@jAndy Thanks. It solved my problem in IE 11 as well. Earlier I used arrow function to remove undefined.
This can be shortened to .filter(n=>n!==undefined)
Someone might get confused, so : The callback function receives the element, that means that doing filter(Boolean) is the same as filter((elem)=>Boolean(elem).
|
152

Inline using lambda

result.filter(item => item);

5 Comments

this one will remove all falsey values. Since the OP specified falsey values being unwanted, this is definitely the best answer IMO. However, thy also specifically point out undefined at which point you'd want result.filter(item => item !== undefined)
[true,false,undefined,null,'a',1,0,'0'].filter(x=>x) returns [true, "a", 1, "0"]
best answer here
JS newby here. People say this is the best answer but why is this better than filter(Boolean) or filter(item => !!item)
@AdamHughes It's not, ppl often overvalue brevity compared to clarity. Of the 3, filter(item => !!item) would actually be the best bc it clearly communicates that you're filtering on the truthiness of item. Boolean would be the worst bc both the input and operation are no longer explicit. Plus it looks like you're filtering for booleans, which is definitely not what it does.
35

You can use lodash compact method, which removes null, undefined and ''.

_.compact(data)

2 Comments

that's not freely available without another library. That's overkill
This works and cleans the array. this is the solution i prefer
32
[NaN, undefined, null, 0, 1, 2, 2000, Infinity].filter(Boolean)
//[ 1, 2, 2000, Infinity ]

1 Comment

years too late for the party and no explanation given for a rather unreadable solution.
25

If you have an array of objects and want to remove all null and undefined items:

[].filter(item => !!item);

Comments

24

ES6 single line

data.filter(e => e)

3 Comments

Careful, this also removes any "falsey" values, like zero. [undefined, null, 0, false].filter(e => e) // []
JavaScript is weird at times :D
This is best for array of objects
24
data.filter(Boolean)

Is the most short and readable way to do it.

5 Comments

Why does this work? Don't just post "magic" explain also how it works and why this is a good solution.
@LucianEnache it applies Boolean function for every item of the array and if it converts to false, it filters it out. Read more here: developer.mozilla.org/ru/docs/Web/JavaScript/Reference/…
Why is the resulting array, still typed as potentially containing undefined?
@SeanMC It's another question, concerning typescript. It doesn't play well with array.filter. You can find additional info on this topic here: stackoverflow.com/questions/43010737/…
The most short way to say most short is shortest. It's also the readablest way.
7

As Diogo Capela said, but where 0 is not filtered out as well.

[].filter(item => item !== undefined && item !== null)

Comments

5

in ES6 this can be achieved by simply using using filter with function return the value like this:

const array = [NaN, 0, 15, false, -22, '',undefined, 47, null];
const filteredArr = array.filter(elm => elm);
console.log(filteredArr);

Comments

4
var a =  ["3","", "6"];
var b =  [23,54,56];
var result = [];

for (var i=0;i<a.length;++i) {
    if (a[i] != "") {
        result[i] = b[i];
    }
}

result = result.filter(function( element ) {
   return element !== undefined;
});

console.log(result);

Comments

4

Array.prototype.reduce() can be used to delete elements by condition from an array but with additional transformation of the elements if required in one iteration.


Remove undefined values from array, with sub-arrays support.

function transform(arr) {
    return arr.reduce((memo, item) => {
        if (typeof item !== "undefined") {
            if (Array.isArray(item)) item = transform(item);
            // We can transform item here.
            memo.push(item);
        }
        return memo;
    }, []);
}

let test1 = [1, 2, "b", 0, {}, "", , " ", NaN, 3, undefined, null, 5, false, true, [1, true, 2, , undefined, 3, false, ''], 10];

console.log(transform(test1));

Try it on jsfiddle.net/bjoy4bcc/

Comments

4
var arr1 = [NaN, 0, 15, false, -22, '',undefined, 47, null];

var array1 = arr1.filter(function(e){ return e;});

document.write(array1);

single lined answer

Comments

3

The solution with Array.filter will actually keep the array unchanged and create a new array without the undesired items. If you want to clean an array without duplicating it, you can use this:

for (var i = data.length-1; i >= 0; i--) {
    if (!data[i]) {
        data.splice(i, 1);
    }
}

Comments

1

If you are in Typescript and want to return an Array of strings vs from Array<string|undefined> try one of these...

var arr = ['a', 'b', 'c', undefined, 'e', undefined, 'g'];
var solutionA = arr.reduce((acc, item) => {
    item && acc.push(item);
    return acc;
}, []);

console.log('solution a', solutionA);

var solutionB = [];
arr.forEach((each) => each && solutionB.push(each), []);

console.log('solution b', solutionB);

arr.forEach((each,index) => (!each) && arr.splice(index,1),[]);
console.log('solution c', arr);

Comments

0

In the Qt - JS implementation:

The filter does not select undefined because it does not hit the lambda so the usual for...of turned out to be preferable:

// B_half.filter(n => { return n !== undefined  })
// B_half.filter(n => n)
// B_half.filter( (n) => { console.log(n); return n })

tree_order = A_half // .concat( B_half )

for ( let ins of B_half ) 
{ 
  if (ins !== undefined) 
  {
    tree_order.push(ins); 
  } 
}

3 Comments

What are A_half and B_half? How do they relate to the data array in the question?
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
If you have a new question, please ask it by clicking the Ask Question button. Include a link to this question if it helps provide context. - From Review
-5
var data = Object.keys(data)

This will remove undefined values but array index will change

1 Comment

Was there supposed to be more code here? All this is going to do is return an array of the numbers 0-6.

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.