Home > Net >  Sort Array of Objects Based on Numeric Value
Sort Array of Objects Based on Numeric Value

Time:07-01

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?

CodePudding user response:

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

  • Related