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"
}]
A simple solution would be to use efficient sorting algorithms like Merge Sort, Quicksort, Heapsort, etc., that can solve this problem in O(n. log(n)) time, but those will not take advantage of the fact that there are many duplicated values in the array. A better approach is to use a counting sort.
IF you mean that you wanted them sorted by id and if the id matches, you want them sorted by name then use this: items. sort(function(a, b) { if (a.id !== b.id) { return a.id - b.id } if (a.name === b.name) { return 0; } return a.name > b.name ?
If you use the native array sort function, you can pass in a custom comparator to be used when sorting the array. The comparator should return a negative number if the first value is less than the second, zero if they're equal, and a positive number if the first value is greater.
Using the indexOf() method In this method, what we do is that we compare the index of all the items of an array with the index of the first time that number occurs. If they don't match, that implies that the element is a duplicate. All such elements are returned in a separate array using the filter() method.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With