Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 808
Remo Williams Avatar asked Jun 05 '26 09:06

Remo Williams


1 Answers

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


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!