I add a element to the array in a higher position than its length
I wonder if is there a way to access or delete this empty elements, I think it can waste memory
I add a element to the array in a higher position than its length
I wonder if is there a way to access or delete this empty elements, I think it can waste memory
When doing this, you create a "sparse array". The items in between the non-null entries contain undefined
. As such, the memory footprint is negligible. You cannot delete them. If you don't like this behavior, just don't create sparse arrays.
For filtering non sparse/dense elements, you could use a callback which returns for every element true
.
Maybe this link helps a bit to understand the mechanic of a sparse array: JavaScript: sparse arrays vs. dense arrays.
let array = new Array(99999),
nonsparse;
array[30] = undefined;
nonsparse = array.filter(_ => true);
console.log(nonsparse);
console.log(nonsparse.length);