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.
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);
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