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 :)
pushis one way to add elements to an array. You need to create a different array first, thenpushto it inside the loop.