1

In Javascript, if I have a very large array, myArray

And I add to it by calling myArray.push()

And I remove indexes using something like delete myArray[102]

Is there some benefit or reason to create a separate array like myArrayGaps that holds which indexes in myArray are not being used so that if there are unused ones, I add to the array by defining a specific index like myArray[102] = newValue; instead of calling .push() and accumulating unused indexes?

Or is that impractical and pointless because of some aspect of Javascript's memory handling?

The reason I am deleting instead of splicing is because I don't want to reorder the indexes of the array; I am using them to identify specific objects at specific indexes. I'm primarily asking if there is any reason to optimize my use of the gaps made when using delete.

c..
  • 1,044
  • 1
  • 9
  • 23

1 Answers1

1

Deleting a property in array using delete array[index] will leave a hole.

Instead you can use splice property which will delete the value in that index and adjust the array size.

As you've mentioned,

var a = [1,2,3,4];
delete a[2];

if you print a now, it will contain [1, 2, undefined × 1, 4]. delete removes the element but doesn't reindex the array/length.

But if you use splice instead,

a.splice(2,1);

It will return you [1, 2, 4]. So you won't find any hole.

mohamedrias
  • 18,326
  • 2
  • 38
  • 47
  • 1
    the reason i'm deleting instead of splicing is because i don't want to reorder the indexes of the array; i am using them to identify specific objects at specific indexes. i'm primarily asking if there is any reason to optimize my use of the gaps. – c.. Apr 05 '15 at 08:47