Search code examples
javascriptarrayssplice

.splice() doesn't shorten my array completly


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

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