Removing undefined values from Array

JavascriptArraysFilter

Javascript Problem Overview


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) ?

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

Inline using lambda

result.filter(item => item);

Solution 3 - Javascript

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

_.compact(data)

Solution 4 - Javascript

ES6 single line

data.filter(e => e)

Solution 5 - Javascript

[NaN, undefined, null, 0, 1, 2, 2000, Infinity].filter(Boolean)
//[ 1, 2, 2000, Infinity ]

Solution 6 - Javascript

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

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

Solution 7 - Javascript

data.filter(Boolean)

Is the most short and readable way to do it.

Solution 8 - Javascript

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

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

document.write(array1);

single lined answer

Solution 9 - Javascript

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

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

Solution 10 - Javascript

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);

Solution 11 - Javascript

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/

Solution 12 - Javascript

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);

Solution 13 - Javascript

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);
    }
}

Solution 14 - Javascript

var data = Object.keys(data)

This will remove undefined values but array index will change

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjAndyView Question on Stackoverflow
Solution 1 - JavascriptjAndyView Answer on Stackoverflow
Solution 2 - JavascriptraphaklausView Answer on Stackoverflow
Solution 3 - JavascriptAkashView Answer on Stackoverflow
Solution 4 - JavascriptRejo ChandranView Answer on Stackoverflow
Solution 5 - JavascriptAnilView Answer on Stackoverflow
Solution 6 - JavascriptDiogo CapelaView Answer on Stackoverflow
Solution 7 - JavascriptYan TakushevichView Answer on Stackoverflow
Solution 8 - JavascriptvishalView Answer on Stackoverflow
Solution 9 - JavascriptTobias WaaentzView Answer on Stackoverflow
Solution 10 - JavascriptJorge LondoñoView Answer on Stackoverflow
Solution 11 - JavascriptBogdan PotishukView Answer on Stackoverflow
Solution 12 - JavascriptROOTView Answer on Stackoverflow
Solution 13 - Javascriptmaxime schoeniView Answer on Stackoverflow
Solution 14 - JavascriptSANTHOSH.SJView Answer on Stackoverflow