Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sort Array of Objects Based on Numeric Value

I have an array like so:

[
   { Orange: 5 },
   { Red: 575 },
   { Green: 6544 },
   { Blue: 1307 }
]

The desired outcome is:

[
   { Green: 6544 },
   { Blue: 1307 },
   { Red: 575 },
   { Orange: 5 }
]

I’ve been trying to use the sort operator after looking through Stack Overflow: myArray.sort((a, b) => a.distance - b.distance). However, the issue I’m running into is the key is not standardized. All the examples I’m finding have the same key but i’m trying to sort on a numeric value with non standard keys.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

When mapping through the above array, I’m able to access the key like so:

let ungroupedArr = [
   { Orange: 5 },
   { Red: 575 },
   { Green: 6544 },
   { Blue: 1307 }
]

ungroupedArr.map(element => {
   //this is the key
   Object.keys(element)[0]
})

I’m trying to get a more verbose sort solution using the above map style logic (where I have access to each element in the array. However, I’ve hit a wall and I’m not sure where to go next.

Any idea how I would go about working this out?

>Solution :

Using Array#sort and Object#values:

const arr = [ { Orange: 5 }, { Red: 575 }, { Green: 6544 }, { Blue: 1307 } ];

const sorted = arr.sort((a, b) => Object.values(b)[0] - Object.values(a)[0]);

console.log(sorted);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading