Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort array of objects by nested property with lodash

I have an array of objects like this

[{ ‘a’: { id: 4 }}, { ‘b’: { id: 3 }}, { ‘c’: { id: 2 }}, { ‘d’: { id: 5 }}]

I want to know with lodash the sorting of the objects according to the id. I would expect to receive something like [‘d’, ‘a’, ‘b’, ‘c’].

I tried to search this but I didn’t find an answer which works with different keys in each object. I tried to do this with lodash’ different functions (many). So I thought there may be a good and maybe short way to solve this.

like image 726
Pichi Wuana Avatar asked Dec 23 '22 00:12

Pichi Wuana


1 Answers

Here is a plain JavaScript solution.

Since you want to get the sorted keys as the result, this solution does not modify the original array, thanks to the first map before sort:

const data = [{ 'a': { id: 4 }}, { 'b': { id: 3 }}, { 'c': { id: 2 }}, { 'd': { id: 5 }}];

const sorted = data
  .map(x => Object.entries(x)[0])
  .sort((a, b) => b[1].id - a[1].id)
  .map(x => x[0]);
  
console.log(sorted);

If you don't care about mutating the original array, you can directly sort using Object.values() and then return the first key with Object.keys():

const data = [{ 'a': { id: 4 }}, { 'b': { id: 3 }}, { 'c': { id: 2 }}, { 'd': { id: 5 }}];

const sorted = data
  .sort((a, b) => Object.values(b)[0].id - Object.values(a)[0].id)
  .map(x => Object.keys(x)[0]);
  
console.log(sorted);
like image 86
jo_va Avatar answered Dec 25 '22 22:12

jo_va