Sort two arrays the same way

前端 未结 12 2238
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-27 15:48

For example, if I have these arrays:

var name = [\"Bob\",\"Tom\",\"Larry\"];
var age =  [\"10\", \"20\", \"30\"];

And I use name.sort

12条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-27 16:43

    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)

提交回复
热议问题