-1

I have a keys array like ['D', 'B', 'A', 'C'] and object like below.

obj = [
    {key: 'C', value: 'CCC'},
    {key: 'B', value: 'BBB'},
    {key: 'D', value: 'DDD'},
    {key: 'A', value: 'AAA'}
]

What is the best way to sort that obj as the order of the keys like below, I prefer to use Lodash.

sorted_obj = [
    {key: 'D', value: 'DDD'},
    {key: 'B', value: 'BBB'},
    {key: 'A', value: 'AAA'},
    {key: 'C', value: 'CCC'}
]

I can think of the way to use additonal data structure like Map, but I really want to make this simple. Does anyone have a nice way to implement this? :)

Anna Lee
  • 909
  • 1
  • 17
  • 37

1 Answers1

3

You can do this quite easily without lodash.

The trick is to prepare a map of key to position in the sorted array (for the given input it is {D: 0, B: 1, A: 2, C: 3}). You can make use of Array.sort() function with a custom compare function then:

const sorted = ['D', 'B', 'A', 'C'];
const obj = [
    {key: 'C', value: 'CCC'},
    {key: 'B', value: 'BBB'},
    {key: 'D', value: 'DDD'},
    {key: 'A', value: 'AAA'}
];

const sortedMap = sorted.reduce((acc, v, idx) => ({...acc, [v]: idx}), {});
const result = obj.sort((a, b) => sortedMap[a.key] - sortedMap[b.key]);

console.log(result);
gurisko
  • 1,172
  • 8
  • 14
  • You can also use `obj.sort((a, b) => sorted.indexOf(a.key) - sorted.indexOf(b.key))` instead of creating a new object. – Harun Yilmaz Oct 06 '20 at 06:39
  • 1
    @HarunYilmaz Which would increase time complexity to quadratic. It all depends on tradeoffs OP is willing to take. – gurisko Oct 06 '20 at 07:05