Slava.In
Slava.In

Reputation: 1069

How to sort the array of objects using several keys at the same time?

I have an array of objects, each has name, skill and talent keys. It looks like this:

 let defaultArray = [
  {name='person1', skill = 6, talent = 3},
  {name='person2', skill = 5, talent = 5},
  {name='person3', skill = 4, talent = 6},
  {name='person4', skill = 2, talent = 7},
  {name='person5', skill = 1, talent = 4},
  {name='person6', skill = 3, talent = 1},
  {name='person7', skill = 6, talent = 2}
]

I need to sort it so that I only have the array of the three best persons defined by their skills, like so:

let resultArray = [
  {name='person1', skill = 6, talent = 3},
  {name='person7', skill = 6, talent = 2},
  {name='person2', skill = 5, talent = 5},
]

As you see if someone's skills are the same (like for person1 and person7 in the defaultArray), then persons are sorted by talent instead.


Can someone, please, help me make a concise function taking defaultArray as a parameter and returning resultArray taking into account that the skill and talent values can be completely random?

Upvotes: 0

Views: 73

Answers (1)

Nilesh Patel
Nilesh Patel

Reputation: 3317

const arr = [
    {name:'person1', skill : 6, talent : 3},
    {name:'person2', skill : 5, talent : 5},
    {name:'person3', skill : 4, talent : 6},
    {name:'person4', skill : 2, talent : 7},
    {name:'person5', skill : 1, talent : 4},
    {name:'person6', skill : 3, talent : 1},
    {name:'person7', skill : 6, talent : 2}
  ];
  

arr.sort((a, b) => (b.skill - a.skill) || (b.talent - a.talent));
console.log(arr)
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 1

Related Questions