Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

229
Views
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.

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!