Sort array of objects by array of IDs [duplicate]

狂风中的少年 提交于 2019-12-10 15:28:59

问题


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"
}]

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"
}]

回答1:


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; }

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; }


来源:https://stackoverflow.com/questions/41097756/sort-array-of-objects-by-array-of-ids

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!