How to Remove 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]

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.