[Solved] JavaScript arrays: how do I compact excess length?


Since nothing in JavaScript specification says length must be exactly one higher than the last index, your demand is not reasonable. In common use, dense arrays overwhelmingly outnumber sparse ones. Since JavaScript does not keep indices in an ordered structure, finding out which index is the last every time array contents change would incur a performance toll in a number of cases where this stronger invariant is not needed.

If you actually need to trim down an array to exclude the trailing non-elements, it is easy enough to do: find the last valid index, and shrink the array yourself:

const a = [0,1,2]
a[99] = 99
delete a[99]
a.length = a.findLastIndex(i => i in a) + 1;
console.log(a);        // [1, 2, 3]
console.log(a.length); // 3

Can it be slow, in case where length is large? Yes. This is precisely why this calculation is not done by default.

EDIT: findLastIndex is not present in all browsers, a workaround or a polyfill might be required.

EDIT2: Better yet, reduce can be employed, which does not call the predicate for the absent indices (and is also present in all current browsers):

const a = [0,1,2]
a[99] = 99
delete a[99]
a.length = a.reduce((l, x, i) => i, 0) + 1;
console.log(a);        // [1, 2, 3]
console.log(a.length); // 3

2

solved JavaScript arrays: how do I compact excess length?