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,
// Update for your needs ('position' to your key).
function updateIndexes( list ) {
list.sort( ( a, b ) => a.position - b.position )
list.forEach( ( _, index, arr ) => {
arr[ index ].position = index
} )
}
var myList = [
{ position: 8 },
{ position: 5 },
{ position: 1 },
{ position: 9 }
]
updateIndexes( myList )
// Result:
var myList = [
{ position: 1 },
{ position: 2 },
{ position: 3 },
{ position: 4 }
]