This might look like a duplicate question, but please don't assume this just because it looks similar to others, and be careful with easy answers unless you really understand the ramifications.
Here is a console dialog to demonstrate the problem:
> a = [0,1,2]
< >(3) [0,1,2]
> a.length
< 3
> a[99] = 99
< 99
> a.length
< 100
> delete a[99]
< true
> a.length
< 99
So this length property of arrays doesn't seem to follow any reasonable specification. Trailing sparse elements should be compacted out, but aren't.
I think as a result, the length property should never be used in code since it is semantically meaningless. (Instead findLastIndex(() => true)
should be used anywhere a naive programmer woul previously use length
.)
I know how to use the elegant forEach, some, every, find, filter, map, and reduce functions. And I know that filter doesn't preserve sparseness. I can use reduce to do a map which can drop elements or a filter which preserves sparseness.
How can we reset the array length property to something reasonable without copying the array?
There may be no answer at all, or rather, the answer may be "there is no way and the array length property is essentially meaningless."