Since using array.splice modifies the array in-place, how can I remove all whitespace-only elements from an array without throwing an error? With PHP we have preg_grep but I
Just simply do this example
// this is you array
let array = ["foo","bar","",""]
// remove blanks in array
let array_new_value = array.join(" ").trim().split(' ');
// Print to know if really works
console.log(array_new_value);
I hope this helps you!!
Another filter based variation - reusable (function)
function removeWhiteSpaceFromArray(array){
return array.filter((item) => item != ' ');
}
a="remove white spaces"
a.split(' ').join('').split('');
It returns an array of all characters in {a="remove white spaces"} with no 'space' character.
You can test the output separately for each method: split() and join().
And for a new generation (namely ES2015):
['1', ' ', 'c'].filter(item => item.trim() !== '')
More on trim()
A better way to "remove whitespace-only elements from an array".
var array = ['1', ' ', 'c'];
array = array.filter(function(str) {
return /\S/.test(str);
});
Explanation:
Array.prototype.filter
returns a new array, containing only the elements for which the function returns true
(or a truthy value).
/\S/
is a regex that matches a non-whitespace character. /\S/.test(str)
returns whether str
has a non-whitespace character.
You removed an item from the array which reduced the array's length. Your loop continued, skipped some indexes (those which were down-shifted into the removed index), and eventually attempted to access an index outside of the new range.
Try this instead:
var src = ["1"," ","2","3"];
var i = src.length;
while(i--) !/\S/.test(src[i]) && src.splice(i, 1);
console.log(src);