按ID数组对对象数组进行排序 [英] Sort array of objects by array of IDs
本文介绍了按ID数组对对象数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以很容易地通过ID数组对对象数组进行排序?这是一个示例:
Is it possible, rather easily, to sort an array of objects by an array of IDs? Here's an example:
[{
id: "A",
name: "John"
}, {
id: "B",
name: "Bobby"
}, {
id: "C",
name: "Peter"
}]
现在我有一个对象数组,每个对象都有一个唯一的ID.然后,我有一个ID数组,如下所示:
Now I have an array of objects, each with an unique ID. I then have an array of IDs like so:
var ids = ["C", "A", "B"];
是否可以对对象数组进行排序,所以最终会像这样:
Would it be possible to sort the array of objects, so it ends up like this:
[{
id: "C",
name: "Peter"
}, {
id: "A",
name: "John"
}, {
id: "B",
name: "Bobby"
}]
推荐答案
您可以使用对象对它进行排序.
You could order it with an object for the sort order.
var data = [{ id: "A", name: "John" }, { id: "B", name: "Bobby" }, { id: "C", name: "Peter" }],
ids = ["C", "A", "B"],
order = {};
ids.forEach(function (a, i) { order[a] = i; });
data.sort(function (a, b) {
return order[a.id] - order[b.id];
});
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
如果ids
数组中只有相同数量的id
,则可以使用分配的索引重新排列数组,而无需进行排序.
If you have only the same amount of id
in the ids
array, then you could just rearrange the array with the assigned indices without sorting.
var data = [{ id: "A", name: "John" }, { id: "B", name: "Bobby" }, { id: "C", name: "Peter" }],
ids = ["C", "A", "B"],
result = [];
data.forEach(function (a) {
result[ids.indexOf(a.id)] = a;
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
这篇关于按ID数组对对象数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文