Remove empty or whitespace strings from array - Javascript
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))));
You can take advantage of empty string as falsy value.
You can use Array#filter
with String#trim
.
Using ES6 Arrow function:
arr = arr.filter(e => String(e).trim());
var arr = ['Apple', ' ', 'Mango', '', 'Banana', ' ', 'Strawberry'];
var nonEmpty = arr.filter(e => String(e).trim());
document.getElementById('result').innerHTML = JSON.stringify(nonEmpty, 0, 4);
<pre id="result"></pre>
Using ES5 anonymous function:
arr = arr.filter(function(e) {
return String(e).trim();
});
var arr = ['Apple', ' ', 'Mango', '', 'Banana', ' ', 'Strawberry'];
var nonEmpty = arr.filter(function(e) {
return String(e).trim();
});
document.getElementById('result').innerHTML = JSON.stringify(nonEmpty, 0, 4);
<pre id="result"></pre>