Having trouble removing values from an array using splice
. I tried using both delete and splice methods but neither seem to work as expected.
var arr = [];
arr[2] = 22;
arr[5] = 3;
arr[99] = 3343;
for(var i in arr){
if(i != 2){
arr.splice(i,1);
}
//delete arr[i];
}
console.log(arr);// [2: 22, 98: 3343]
//wanted [2:22]
I am attempting to remove all elements from the array except the one at index 2
, however it only deletes one element. Any suggestions on how to achieve this?