Sort two arrays the same way

前端 未结 12 2239
爱一瞬间的悲伤
爱一瞬间的悲伤 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:34

    You could append the original index of each member to the value, sort the array, then remove the index and use it to re-order the other array. It will only work where the contents are strings or can be converted to and from strings successfuly.

    Another solution is keep a copy of the original array, then after sorting, find where each member is now and adjust the other array appropriately.

提交回复
热议问题