EN
JavaScript - remove empty elements from array
3
points
In this article, we would like to show you how to remove empty elements from an array in JavaScript.
Quick solution:
const outputArray = inputArray.filter(x => x);
Alternative solutions
When we want to keep zeros too:
const outputArray = inputArray.filter(x => x || x === 0);
When we want to keep empty strings too:
const outputArray = inputArray.filter(x => x || x === '');
Practical example
In this example, we use filter()
method to create a copy of the values
array without empty elements.
// ONLINE-RUNNER:browser;
const values = ['A', 'B', 1, -2, 0, null, undefined,,,, '', "", 'C', 'D'];
const result = values.filter(x => x);
console.log(result); // [A,B,1,-2,C,D]