What is the best method to sort a sparse array and keep the elements on the same indexes? For example:
a[0] = 3,
a[1] = 2,
a[2] = 6,
a[7] = 4,
a[8] = 5,
I would like after the sort to have
a[0] = 2,
a[1] = 3,
a[2] = 4,
a[7] = 5,
a[8] = 6.
Here's one approach. It copies the defined array elements to a new array and saves their indexes. It sorts the new array and then puts the sorted results back into the indexes that were previously used.
Working demo: http://jsfiddle.net/jfriend00/3ank4/
You can
filter
orObject.values
to obtain an array with the values of your sparse array.sort
that array, from largest to smaller. Be aware it's not stable, which may be specially problematic if some values are not numeric. You can use your own sorting implementation.map
andpop
to obtain the desired array. Assign it toa
.Or, in ECMAScript 2017,