Force an array to recalcuate length after sort
Posted
by
Rhyono
on Stack Overflow
See other posts from Stack Overflow
or by Rhyono
Published on 2012-09-13T03:21:01Z
Indexed on
2012/09/13
3:39 UTC
Read the original article
Hit count: 123
JavaScript
|google-chrome
If you take an array and do the following:
arr = [];
arr[100] = 1;
The length will be 101, which makes sense due to 0-99 being set as undefined
Now if we sort that array: arr.sort()
it will look like this: [1, undefined x100]
since keys are not preserved. However, the length is still 101, since the undefined
have all been moved to the end, instead of removed.
Is this behavior intentional and if so: is there a built-in function that removes undefined
and recalculates and why is it intentional?
I am not asking how to write my own function to recalculate length. A sorted array's length can easily be forced with for (x = 0; arr[x] != undefined; x++);arr.length = x;
© Stack Overflow or respective owner