Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove empty or whitespace strings from array - Javascript

Tags:

I've found this beautiful method for removing empty strings - arr = arr.filter(Boolean).

But it doesn't seem to work on whitespace strings.

var arr = ['Apple', '  ', 'Mango', '', 'Banana', ' ', 'Strawberry']; arr = arr.filter(Boolean); // ["Apple", "  ", "Mango", "Banana", " ", "Strawberry"]  // should be ["Apple", "Mango", "Banana", "Strawberry"] 

Is there a nice way to expand this method to removing whitespaces as well or should i trim the whitespaces by iterating the array first?

like image 954
Daniel Avatar asked Feb 18 '16 09:02

Daniel


People also ask

How do you remove Blank strings from an array?

To remove the empty strings from an array, we can use the filter() method in JavaScript. In the above code, we have passed the callback function e => e to the filter method, so that it only keeps the elements which return true . empty "" string is falsy value, so it removes from the array.

How do you get rid of all whitespace in a string JavaScript?

JavaScript String trim() The trim() method removes whitespace from both sides of a string. The trim() method does not change the original string.


1 Answers

filter works, but you need the right predicate function, which Boolean isn't (for this purpose):

// Example 1 - Using String#trim (added in ES2015, needs polyfilling in outdated // environments like IE) arr = arr.filter(function(entry) { return entry.trim() != ''; }); 

or

// Example 2 - Using a regular expression instead of String#trim arr = arr.filter(function(entry) { return /\S/.test(entry); }); 

(\S means "a non-whitespace character," so /\S/.test(...) checks if a string contains at least one non-whitespace char.)

or (perhaps a bit overboard and harder to read)

// Example 3 var rex = /\S/; arr = arr.filter(rex.test.bind(rex)); 

With an ES2015 (aka ES6) arrow function, that's even more concise:

// Example 4 arr = arr.filter(entry => entry.trim() != ''); 

or

// Example 5 arr = arr.filter(entry => /\S/.test(entry)); 

Live Examples -- The ES5 and earlier ones:

var arr = ['Apple', '  ', 'Mango', '', 'Banana', ' ', 'Strawberry']; console.log("Example 1: " + JSON.stringify(arr.filter(function(entry) { return entry.trim() != ''; }))); console.log("Example 2: " + JSON.stringify(arr.filter(function(entry) { return /\S/.test(entry); }))); var rex = /\S/; console.log("Example 3: " + JSON.stringify(arr.filter(rex.test.bind(rex))));

...and the ES2015 (ES6) ones (won't work if your browser doesn't support arrow functions yet):

var arr = ['Apple', '  ', 'Mango', '', 'Banana', ' ', 'Strawberry']; console.log("Example 4: " + JSON.stringify(arr.filter(entry => !entry.trim() == ''))); console.log("Example 5: " + JSON.stringify(arr.filter(entry => /\S/.test(entry))));
like image 194
T.J. Crowder Avatar answered Oct 12 '22 18:10

T.J. Crowder