Best way to remove an element from an array without reordering it

I need to remove some elements of my array, but without a reordered array.

If I use delete to delete my elements, do holes occupy memory?

var array=["A","B","C"]; delete array[1]; // array -> ["A", undefined, "C"] 

I think the deleted item is really deleted, so it does not take up memory, right?

+6
javascript arrays
source share
3 answers

It depends entirely on the implementation. Internally, all JS views end up being converted to a sparse view, but the sparese view tends to use more memory for each item and be slower to access than a non-sparse array.

For this reason, deleting a single value from a dense array is unlikely to free up any memory, but after removing a sufficient set of elements, the implementation is likely to be converted to a sparse representation to save memory in general.

Note: the object or value in the index you are deleting will not be deleted immediately - deleting simply removes the property slot from the object - the object / value will be deleted only during the passage of the GC, and only if there are no other links.

+4
source share

Try using

 array.splice(index, 1); 

See Mastering JavaScript Arrays .

+9
source share

You can use array.splice(1, 1); It will delete one entry with index 1. The first parameter is the index, the second is the score.

+3
source share

All Articles