Reputation: 1593
I have an array with Strings, if there is nothing written in the String I want to remove it from the array with .splice()
.
Somehow it does not get all empty entries. If there are 2 empty entries in the beginning, it only gets one.
Here is my fiddle and code:
stringArray = ["", "", "Banana"];
console.log('before stringArray.length: ' + stringArray.length);
for (var i = 0; i < stringArray.length; i++) {
if (stringArray[i] === "") {
stringArray.splice(i, 1);
if (i > 0) i--;
}
}
console.log('after stringArray.length: ' + stringArray.length);
Upvotes: 1
Views: 678
Reputation: 50905
Another option, of course with looping backwards, is with a while
loop:
var stringArray = ["", "", "", "Apple", "", "", "Banana", "", "", ""];
var i = stringArray.length;
while (i-- && (stringArray[i] !== "" || stringArray.splice(i, 1)));
console.log(stringArray); // ["Apple", "Banana"]
DEMO: http://jsfiddle.net/VEmAV/
Upvotes: 2
Reputation: 71918
You have to loop backwards, because every time you splice
, the length and indexes change:
for (var i = stringArray.length-1; i>=0; i--) {
if(stringArray[i] === ""){
stringArray.splice(i, 1);
}
}
Alternate solution with Array.prototype.filter
(documentation page provides a shim for old browsers that won't support this method):
stringArray = [ "","","Banana"];
var a = stringArray.filter(function(item) {
return item !== '';
});
console.log(a);
Upvotes: 6