Remo Williams
Remo Williams

Reputation: 235

Trouble removing elements from multidimensional array using for loop (javascript)

I'm banging my noob head against the wall on this one...

I have the following code:

var guns2 = 
[
["Model 17", "Glock"],
["Model 19", "Glock"],
["PPQ", "Walther"],
["P2000", "HK"],
["Model 92", "Beretta"],
["Model 34", "Glock"]
]

var gunsMake = function () {
    for (i=0; i<guns2.length; i++){
        var make = guns2[i][1];
            if (make ==="Glock"){
                }
            else {
                guns2.splice(i,1);
                }
        };
    };
gunsMake();
console.log(guns2);

The result I get in the console is as follows:

[["Model 17", "Glock"], ["Model 19", "Glock"], ["P2000", "HK"], ["Model 34", "Glock"]]

What I'd like to see is:

[["Model 17", "Glock"], ["Model 19", "Glock"], ["Model 34", "Glock"]]

"["P2000", "HK"]" shouldn't be there...I have a feeling it has something to do with the "guns2.length" argument in the for loop..it seems like it's skipping the subsequent array every time it splices, but I can't quite wrap my brain around a fix.

Please, someone steer me right :)

Upvotes: 2

Views: 6323

Answers (3)

user1726343
user1726343

Reputation:

It usually isn't a good idea to modify an array while you're iterating over it, since it becomes hard to keep track of indices and exit conditions. Either insert desired results into a separate array, or use the native filter method to return a filtered array.

var gunsMake = function (guns, desiredMake) {
    return guns.filter(function(v,i,a){
        return v[1] == desiredMake;
    });
};
guns2 = gunsMake(guns2, "Glock");
console.log(guns2);

More on the Array filter method on MDN: Array filter method

Upvotes: 6

Trevor Dixon
Trevor Dixon

Reputation: 24352

It's not always awful to modify the array in-place. If that's what you decide to do, decrement i when you remove an element.

http://jsfiddle.net/kVzLn/

var guns2 = 
[
["Model 17", "Glock"],
["Model 19", "Glock"],
["PPQ", "Walther"],
["P2000", "HK"],
["Model 92", "Beretta"],
["Model 34", "Glock"]
]

var gunsMake = function () {
    for (i=0; i<guns2.length; i++){
        var make = guns2[i][1];
            if (make ==="Glock"){
                }
            else {
                guns2.splice(i--,1); // Decrement i here
                }
        };
    };
gunsMake();
console.log(guns2);

Upvotes: 3

Luke Z
Luke Z

Reputation: 2419

You're deleting (splicing) nodes out of your array while you're looping through it with a fixed index. So, you're not checking all of the elements.

If you check element #1 and decide to delete it, then when you check #2 you're actually checking #3.

Upvotes: 1

Related Questions