How to Remove undefined Values From a JavaScript Array?

Quick tip to filter out undefined values from a JavaScript array

Using filter()

To remove undefined values from a JavaScript array, you can simply use the filter() method like so:

// ES5+
const arr = [1, undefined, 2, 3, undefined, 5];

const filteredArr = arr.filter(function (elem) {
    return elem !== undefined;
});

console.log(filteredArr); // output: [1, 2, 3, 5]

Or alternatively, you can use the arrow function syntax (introduced in ES6) for a one-liner like the following:

// ES6+
const arr = [1, undefined, 2, 3, undefined, 5];

const filteredArr = arr.filter((elem) => elem !== undefined);

console.log(filteredArr); // output: [1, 2, 3, 5]

Using for Loop

If you're unable to use the latest features of JavaScript, then you can use a for loop to create a new array with filtered values. For example:

const arr = [1, undefined, 2, 3, undefined, 5];

const filteredArr = [];

for (let i=0; i<arr.length; i++) {
    if (arr[i] !== undefined) {
        filteredArr.push(arr[i]);
    }
}

console.log(filteredArr); // output: [1, 2, 3, 5]

Hope you found this post useful. It was published . Please show your love and support by sharing this post.