Daniel Daniel - 17 days ago 7
Javascript Question

Remove empty or whitespace strings from array - Javascript

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?

Answer

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

// Example 1
arr = arr.filter(function(entry) { return entry.trim() != ''; });

or

// Example 2
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));

In ES2015 (aka ES6), 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'];
snippet.log("Example 1: " + JSON.stringify(arr.filter(function(entry) { return entry.trim() != ''; })));
snippet.log("Example 2: " + JSON.stringify(arr.filter(function(entry) { return /\S/.test(entry); })));
var rex = /\S/;
snippet.log("Example 3: " + JSON.stringify(arr.filter(rex.test.bind(rex))));
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

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

var arr = ['Apple', '  ', 'Mango', '', 'Banana', ' ', 'Strawberry'];
snippet.log("Example 4: " + JSON.stringify(arr.filter(entry => !entry.trim() == '')));
snippet.log("Example 5: " + JSON.stringify(arr.filter(entry => /\S/.test(entry))));
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

Comments