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

JavaScript – Giving an array of objects a rating based on numerical value and incrementing the rating for duplicates

    {
        "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

    },

]

>Solution :

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

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