Sort array of objects by array of IDs [duplicate]

2019-07-12 19:47发布

This question already has an answer here:

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条回答
地球回转人心会变
2楼-- · 2019-07-12 20:08

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

查看更多
登录 后发表回答