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