12

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"
}]
MortenMoulder
  • 6,138
  • 11
  • 60
  • 116
  • 5
    [`arr.sort((a, b) => ids.indexOf(a.id) > ids.indexOf(b.id))`](https://jsfiddle.net/tusharj/2uqhnnqy/) – Tushar Dec 12 '16 at 09:35
  • `data.sort(function(a,b) { return ids.indexOf(a.id) > ids.indexOf(b.id); })` – haim770 Dec 12 '16 at 09:35
  • 1
    Also see [Sort array containing objects based on another array](//stackoverflow.com/q/13518343), [How do I sort an array of objects based on the ordering of another array?](//stackoverflow.com/q/9755889), [Sort an array of objects based on another array of ids](//stackoverflow.com/q/35538509), [JavaScript - Sort an array based on another array of integers](//stackoverflow.com/q/4046967) – Tushar Dec 12 '16 at 09:40

1 Answers1

18

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; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392