1

I add a element to the array in a higher position than its length

enter image description here

I wonder if is there a way to access or delete this empty elements, I think it can waste memory

Juan Velasquez
  • 385
  • 4
  • 15

2 Answers2

0

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.

Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
0

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • But this really doesn't address the question. *I wonder if is there a way to access or delete this empty elements, I think it can waste memory* – Scott Marcus Oct 23 '18 at 20:47
  • do you mention the memory part? if yes, the yes ... i like tautologies, but *"I wonder if is there a way to ... delete this empty elements"* – Nina Scholz Oct 23 '18 at 20:48
  • I mentioned both parts. Your answer just shows how to create a second array with the non-undefined data from the first. It doesn't address either points. – Scott Marcus Oct 23 '18 at 20:50