muelleste
muelleste

Reputation: 41

JS Splice an Array

I wanted to splice my array, so I created this snippet of code:

System.log(finalcluster.length);
for (i=0; i <= finalcluster.length; i++){
    if (finalcluster[i] != undefined ){
        System.log(finalcluster[i][0]);
        var remove = finalcluster.indexOf("dump");
        if (finalcluster[i][0] == "dump")
        {
            System.log("couse dump");
            finalcluster.splice(remove,1);
        }
        else {
            System.log("No Problem");
        }
    }
}

In this code are two remove functions, I know because I tried indexof an integer i.

When I executed this code, only two dumps are removed, I think the two before but after my right result, there are another "dump" arrays. Why split can't move it because it can splice the array from before the key word.

Array:

[Name][Number]
[dump][0]
[dump][0]
[KEYWORD][KEYNUMBER]
[dump][0]
[dump][0]

that's the array model.

Upvotes: 3

Views: 212

Answers (2)

Rob M.
Rob M.

Reputation: 36511

One problem with your code is that you are iterating finalcluster in ascending order using finalcluster.length while changing (decrementing) the array's length. Because of this, each time your remove condition is met the number of times the loop runs goes down by 1 which makes the tail of your array unreachable. Example:

// seems like this would empty out the array
let arr = [1, 2, 3, 4]
for (let i = 0; i < arr.length; i++) {
   arr.splice(i, 1)
}

console.log(arr); // [2, 4]

You can avoid this issue by iterating over finalcluster in reverse order

let arr = [1, 2, 3, 4]
for (let i = arr.length - 1; i >= 0; i--) {
   arr.splice(i, 1)
}

console.log(arr)

Upvotes: 1

Matt
Matt

Reputation: 1082

You either need to increment i if you don't splice or splice and decrement i. As of right now you are splicing and incrementing which is skipping your back-to-back dumps.

To try to explain it better you are saying dump is at index 1 and 2. If you splice at 1, what was at index 2 is now at index 1 but you are making i look at index 2....

System.log(finalcluster.length);
    for (i=0; i <= finalcluster.length;){
        if (finalcluster[i] != undefined ){
            System.log(finalcluster[i][0]);
            var remove = finalcluster.indexOf("dump");

            if (finalcluster[i][0] == "dump"){
                System.log("couse dump");
                finalcluster.splice(remove,1);

            }else {
                System.log("No Problem");
                i++;
            }
        }
    }

The code above will increment i if you do not splice. otherwise it keeps i at its current index to avoid skipping indexes.

Upvotes: 0

Related Questions