Given an array of objects and a list of values, I want to effectively sort the object so that values of a unique property (say key) follows the order of values in the list.
So for an array:
const users = [
{ key: 'A', name: 'Alice' },
{ key: 'B', name: 'Bob' },
{ key: 'C', name: 'Charlie' },
]
I'd like the function to behave like this:
sortByList(['A', 'B', 'C'], users)
// -> Objects for Alice, Bob, Charlie
sortByList(['C', 'B', 'A'], users)
// -> Objects for Charlie, Bob, Alice
sortByList(['A', 'C', 'B'], users)
// -> Objects for Alice, Charlie, Bob
I came up with an implementation that uses Array::sort on the array and then inside Array::indexOf on the list.
const users = [
{ key: 'A', name: 'Alice' },
{ key: 'B', name: 'Bob' },
{ key: 'C', name: 'Charlie' },
]
const sortByList = (list, arr) => arr.sort(
(a, b) => list.indexOf(a.key) - list.indexOf(b.key)
);
sortByList(['C', 'B', 'A'], users)
console.log(users)
But I feel this is not an effective solution. The time complexity is O(N^2*log(N)) which is rather high. Is there a better one?
I do not care about in-place sorting or stability, imagine the array has tens to hundreds of items.
Schwartzian transformto sort this array.const sortByList = (list, arr) => arr .map(o => [list.indexOf(o.key), o]) .sort(([a], [b]) => a - b) .map(([,o]) => o);