根据另一个数组对对象数组进行排序

时间:2015-01-03 15:51:39

标签: javascript jquery arrays sorting

我有两个这样的数组:

objects = [Obj1, Obj2, Obj3];
scores  = [10,200,15];

对象[i]对应于得分[i]中的得分。

我需要按降序排列对象数组,具体取决于它们的相对分数。

任何想法如何在jQuery / javascript中有效地做到这一点? 谢谢你的帮助!

1 个答案:

答案 0 :(得分:2)

正如@Rory McCrossan所暗示的那样,最好的方法可能是将这些值加在一起然后根据需要将它们分开:

// produces [{score: 10,  value: Obj1}, 
//           {score: 200, value: Obj2},
//           {score: 15,  value: Obj3}]
var joined = objects.map(function (el, i) {
    return { score: scores[i], value: el };
});

// rearranges joined array to:
//          [{score: 200, value: Obj2},
//           {score: 15,  value: Obj3},
//           {score: 10,  value: Obj1}]
joined.sort(function (l, r) { return r.score - l.score; });

// produces [Obj2, Obj3, Obj1]
var sorted = joined.map(function (el) { return el.value; });
相关问题