JavaScript的数组排序与顺序排列对齐 [英] javascript sort array to align with order array
问题描述
下面是一个例子:
// 0 1 2 3 4
var people = ['jack','jill','nancy','tom','cartman'];
var order = [3,1,4,0,2];
// somehow sort people array to the order specified in the order array
// 3 1 4 0 2
people == ['tom','jill','cartman','jack','nancy'];
我以前用过的.sort具有的功能,但我仍然在这一个损失。
I have used .sort with a function before, but am still at a loss on this one.
更新
看到一些答案后,我简直不敢相信这不是明显对我。所以,因为有许多方法可以做到这一点,获奖者将被jsperf决定。
after seeing some answers, I can't believe this was not obvious to me. So as there are many ways to do this, winner will be determined by jsperf.
(也是我upvoting大家一起工作的答案)
(also I am upvoting everyone with a working answer)
的比赛! http://jsperf.com/array-sorted-to-order-array3
The RACE! http://jsperf.com/array-sorted-to-order-array3
推荐答案
订单
是索引数组。因此,只要通过迭代,拉出你想要的值spcified的顺序,使得一个新的数组。
order
is an array of indicies. So just iterate through that, pulling out the values you want in the order spcified, making a new array.
var people = ['jack','jill','nancy','tom','cartman'];
var order = [3,1,4,0,2];
var sorted = [];
for (var i = 0; i < order.length; i++) {
var desiredIndex = order[i];
sorted.push(people[desiredIndex]);
}
console.log(sorted);
// ["tom", "jill", "cartman", "jack", "nancy"]
有时排序是不是排序。有时候,你只需要通过从你的其他事情拉取数据做一个新的东西。
Sometimes sorting isn't "sorting". Sometimes you just need to make a new thing by pulling data from your other things.
这篇关于JavaScript的数组排序与顺序排列对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!