For example, if I have these arrays:
var name = [\"Bob\",\"Tom\",\"Larry\"];
var age = [\"10\", \"20\", \"30\"];
And I use name.sort
You could get the indices of name
array using Array.from(name.keys())
or [...name.keys()]
. Sort the indices
based on their value. Then use map
to get the value for the corresponding indices in any number of related arrays
const indices = Array.from(name.keys())
indices.sort( (a,b) => name[a].localeCompare(name[b]) )
const sortedName = indices.map(i => name[i]),
const sortedAge = indices.map(i => age[i])
Here's a snippet:
const name = ["Bob","Tom","Larry"],
age = ["10", "20", "30"],
indices = Array.from(name.keys())
.sort( (a,b) => name[a].localeCompare(name[b]) ),
sortedName = indices.map(i => name[i]),
sortedAge = indices.map(i => age[i])
console.log(indices)
console.log(sortedName)
console.log(sortedAge)