Reputation: 3446
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 am lost as to how and do this correctly in JS.
The following will not work because of above reason:
for (var i=0, l=src.length; i<l; i++) {
if (src[i].match(/^[\s\t]{2,}$/) !== null) src.splice(i, 1);
}
Error:
Uncaught TypeError: Cannot call method 'match' of undefined
Upvotes: 20
Views: 64714
Reputation: 1
function clearSpace(arr){
for (var key in arr) {
if (arr[key] == "") {
arr.splice(key, 1)
clearSpace(arr)
}
}
}
var arr = ["","a","b","",""]
clearSpace(arr)
//I hope this helps you!!
//Vu Tien Luong - 3GTEL
Upvotes: 0
Reputation: 1
Here's another approach.
var data = JSON.parse(arrayval.split(/\s/).join(''));
Upvotes: 0
Reputation: 1272
const words = ['spray', 'limit', 'elite', 'exuberant', ' ', ''];
const result = words.filter(word => word.trim().length > 0);
console.log(result);
Upvotes: 4
Reputation: 312
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!!
Upvotes: 1
Reputation: 51
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().
Upvotes: 3
Reputation: 41675
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);
Upvotes: 2
Reputation: 1546
Another filter based variation - reusable (function)
function removeWhiteSpaceFromArray(array){
return array.filter((item) => item != ' ');
}
Upvotes: 5
Reputation: 8494
And for a new generation (namely ES2015):
['1', ' ', 'c'].filter(item => item.trim() !== '')
Upvotes: 0
Reputation: 83245
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.
Upvotes: 34