I have to delete some elements of my array, but without rearrange array.
If I use "delete" to delete my elements, the "holes" take up memory?
var array=["A","B","C"];
delete array[1]; // array -> ["A", undefined, "C"]
I think the deleted element is really deleted so it isn't take up memory space, isn't true?
I have to delete some elements of my array, but without rearrange array.
If I use "delete" to delete my elements, the "holes" take up memory?
var array=["A","B","C"];
delete array[1]; // array -> ["A", undefined, "C"]
I think the deleted element is really deleted so it isn't take up memory space, isn't true?
Share Improve this question edited Aug 11, 2014 at 8:50 Sam 7,39816 gold badges47 silver badges68 bronze badges asked Oct 28, 2009 at 19:01 blowblow 13.2k25 gold badges80 silver badges115 bronze badges4 Answers
Reset to default 10Try using,
array.splice(index, 1);
See Mastering JavaScript Arrays.
Entirely implementation dependent. Internally all JS representations will eventually convert to a sparse representation, but the sparese representation tends to use more memory per element and be slower to access than the non-sparse array.
For this reason removing onevalue from a dense array is unlikely to releas any memory, but after a sufficient set of elements are removed the implementation will likely convert to a sparse representation to save memory overall.
Note: the object or value at the index you delete won't be deleted immediately -- delete simply removes the property slot from the object -- the object/value will only be removed during a GC pass, and only if there are no other references.
You can use array.splice(1, 1);
It will remove one entry at index 1. The first parameter is the index, the second one is the count.
There can be many ways to do it. One of them is to create slices of the array excluding the index and then concatenate the slices.
var arr = ["A", "B", "C"];
const idx = 1;
//Before
console.log(arr);
arr = arr.slice(0, idx).concat(arr.slice(idx + 1));
//After
console.log(arr);