JavaScript的 - 排序基于另一个整数数组的数组 [英] JavaScript - Sort an array based on another array of integers
本文介绍了JavaScript的 - 排序基于另一个整数数组的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说我有一个数组: [0,3,4,2,5,1]
我想要做的是数组排序,如:
What i want to do is sort an array such as:
["one", "two", "three", "four", "five", "six"]
,使得顺序对应于第一阵列
so that the order corresponds to the first array.
这将是输出:
["one", "four", "five", "three", "six", "two"]
有一个简单的方法来做到这一点?
Is there an easy way to accomplish this?
推荐答案
您可以做这样的事情:
function getSorted(arr, sortArr) {
var result = [];
for(var i=0; i<arr.length; i++) {
result[i] = arr[sortArr[i]];
}
return result;
}
你可以在这里测试它。
的注意:的这一假设您传递的大小相当于数组,你需要添加一些额外的检查,这可能并非如此。
Note: this assumes the arrays you pass in are equivalent in size, you'd need to add some additional checks if this may not be the case.
这篇关于JavaScript的 - 排序基于另一个整数数组的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文