Home > Back-end >  How to sort an array of objects on the basis of the number value in the object
How to sort an array of objects on the basis of the number value in the object

Time:10-01

If I have an array of:

var arr = [{"apple":3}, {"pear":5}, {"orange":1}]

How can I sort this array based on the number value inside the objects desc order?

I want the sorted array to be:

[{"pear":5}, {"apple":3}, {"orange":1}]

CodePudding user response:

Try this.

const newArr = arr.sort((a, b) => {
return Object.values(b)[0] -  Object.values(a)[0];
});

CodePudding user response:

You need to create another variable, then run the array variable with .reverse(); at the end.

CodePudding user response:

Just a reference for you,waiting for more elegant solution to it

var arr = [{"apple":3}, {"pear":5}, {"orange":1}]
arr.sort((a,b)=>{
  //return b[Object.keys(b)[0]] - a[Object.keys(a)[0]]
  return Object.values(b)[0] -  Object.values(a)[0];
})

console.log(arr)

  • Related