Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort array of objects by array of IDs [duplicate]

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"
}]
like image 635
MortenMoulder Avatar asked Dec 12 '16 09:12

MortenMoulder


People also ask

How will you sort an array with many duplicated values?

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.

How do you sort an array of objects based on ID?

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 ?

How do you sort an array of objects based on another array?

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.

How do you find duplicate objects in an array?

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.


1 Answers

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; }
like image 185
Nina Scholz Avatar answered Oct 02 '22 07:10

Nina Scholz