1

If I have an array and I delete certain elements, I end up with an array that has non-consecutive keys:

var arr = [15,16,20,21,-1];
delete arr[1];
delete arr[3];
console.log(arr);
// [0: 15, 2: 20, 4: -1]

How can I "reset" the array's keys?

I should end up with an array like so:

[0: 15, 1: 20, 2: -1]
Codemonkey
  • 4,455
  • 5
  • 44
  • 76

3 Answers3

8

For example, you can use Array.prototype.filter method.

var array = [];
array[30] = 1;
array.length; // 31

var compactArray = array.filter(function (item) {
    return item !== undefined;
});

compactArray.length; // 1

If it's an object, for..in loop will be usefull

var array = { 31: 1};
var compactArray = [];
for (var i in array) {
    compactArray.push(array[i]);
}
Martin Schulz
  • 582
  • 1
  • 3
  • 13
1

You can loop throw array and if its a valid item, then push in another array.

Also, when you do something like this,

var arr = [];
arr[3] = 15;

arr is actually [null, null, null, 15]

Following is an example.

(function() {
  var arr = [];
  var result = [];

  arr[3] = 15;
  arr[7] = 20;
  arr[19] = -1;

  console.log(arr);
  console.log(JSON.stringify(arr))

  arr.forEach(function(item) {
    if (item) {
      result.push(item);
    }
  })

  console.log(result);
  console.log(JSON.stringify(result));
})()
Rajesh
  • 24,354
  • 5
  • 48
  • 79
0

if you mean your object is like this

var obj = {3: 15, 7: 20, 19: -1};
var output = {};
var counter = 0;
for ( var id in obj )
{
   output[ String( counter ) ] = obj[ id ];
   counter++;
}
console.log( output );
gurvinder372
  • 66,980
  • 10
  • 72
  • 94