Question

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);
Was it helpful?

Solution

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);

OTHER TIPS

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/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top