{
"name": John,
"awards": 3
},
{
"name": Pat,
"awards": 9
},
{
"name": Mary,
"awards": 2
},
{
"name": Joe,
"awards": 1
},
{
"name": Kathleen,
"awards": 1
},
{
"name": Teddy,
"awards": 1
},
]
Hi, how do i sort this array of objects and add a new attribute to each object called score, giving each of them a score between 1 and 6, if some objects have the same score the next score needs to increment by the number of value with the same score. This is an example of how i need the output to be. Thanks
{
"name": John,
"awards": 3,
"score": 5
},
{
"name": Pat,
"awards": 9,
"score": 6
},
{
"name": Mary,
"awards": 2,
"score": 4
},
{
"name": Joe,
"awards": 1,
"score": 1
},
{
"name": Kathleen,
"awards": 1,
"score": 1
},
{
"name": Teddy,
"awards": 1,
"score": 1
},
]
CodePudding user response:
Sort, then assign the index as the score, unless the previous entry is equal, in that case take over their score:
const byAward = (a, b) => a.awards - b.awards;
winners.sort(byAward);
winners.forEach((winner, index) => {
if (index === 0 || byAward(winner, winners[index - 1]) !== 0)
winner.score = index 1;
else
winner.score = winners[index - 1].score;
});