-4

Stuck in delete array value by splice .Tried with delete and splice doesn't work..

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 want to delete all except index 2 ,It is only delete one.

Jack jdeoel
  • 4,554
  • 5
  • 26
  • 52

2 Answers2

1

No need of a for loop in the splice, you may use: arr.splice(0,arr.length)

But if you want to just delete all elements just do arr=[].

Alternative method would be to loop & pop:

while(arr.length > 0) {
    arr.pop();
}
Ani Menon
  • 27,209
  • 16
  • 105
  • 126
0

In the case you might need to get a sequential item by item deletion starting from the the middle of an array you should iterate in reverse in order not to get the shifting indexes get in front of you.

var arr = new Array(10).fill("").map((e,i) => e = "item:" +i),
      i = 7;
console.log(JSON.stringify(arr));
while (i>2) console.log(JSON.stringify(arr.splice(i--,1))); // splice item at index i and decrease i by one
console.log(JSON.stringify(arr));
  
Redu
  • 25,060
  • 6
  • 56
  • 76