0

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?

2
  • 2
    Welcome to Stack Overflow! You should not ask people to write code for you. You should first attempt this yourself, then if you have any problems, we will be glad to help. As a starting point, sort the array by talent then by skill. Commented Dec 25, 2020 at 12:37
  • You should showcase how much have you delved into figuring sorting & custom comparators in JS. If you are a newbie to JS, start here: mdn reference on sorting Commented Dec 25, 2020 at 12:42

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.