Hello Friends đź‘‹,

Welcome to Infinitbility.

In this tutorial, we will see how we can remove spaces from an array in javascript.

To remove space from the array we will use multiple javascript concepts like an iterated array, remove useless space, and falsy methods.

JavaScript provides a filter() method to filter array elements by some condition, where we will write our space condition.

filter() method returns a new array based on your condition.

let take the following array example.

var arr = ['Apple', '  ', 'Mango', '', 'Banana', ' ', 'Strawberry'];

Here, I will share which I got two better methods to filter space from the array.

var arr = ['Apple', '  ', 'Mango', '', 'Banana', ' ', 'Strawberry'];

//  ES6
arr = arr.filter(e => String(e).trim());

// ES5
arr = arr.filter(function(e) {
    return String(e).trim();
});

Output

Javascript remove space from array example
Javascript remove space from array example

Thanks for reading….