按 ID 数组对对象数组进行排序 [英] Sort array of objects by array of IDs

查看:57
本文介绍了按 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆