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 object by key

So I have this array of objects

[
  {
    '1485958472927784961': {
      name: 'bruno fiverr',
      points: 6,
      user_id: '1485958472927784961',
      tweets: [Array]
    },
    '1414575563323420679': {
      name: 'ju',
      points: 7,
      user_id: '1414575563323420679',
      tweets: [Array]
    }
  }
]

and I would like to sort this array by the number of points the user has.
I am trying to get it working using array.sort with the following function:

var top10 = array.sort(function(a, b) { return a.points > b.points ? 1 : -1; }).slice(0, 10);

but all I get is the same array from start. is that possible?

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

>Solution :

You have an array with a single object whose values you want to sort by a property. For that you’ll want to:

  1. Access the first object in the outer array with array[0]
  2. Extract the values of the object as an array with Object.values
  3. Sort the values in descending order with the sort function (a,b) => b.points - a.points
  4. Obtain your 10 elements with .slice(0,10)
const array = [
  {
    '1485958472927784961': {
      name: 'bruno fiverr',
      points: 6,
      user_id: '1485958472927784961',
      tweets: [Array]
    },
    '1414575563323420679': {
      name: 'ju',
      points: 7,
      user_id: '1414575563323420679',
      tweets: [Array]
    }
  }
];

const top10 = Object.values(array[0]).sort((a,b) => b.points - a.points).slice(0,10);

console.log(top10);
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