Skip to content
Advertisement

Object’s values sorted in desecending order

I have this object:

gladiators = {
  Pesho: { Duck: '400' },
  Gladius: { Heal: '200', Support: '250', Shield: '250' }
}

Each gladiator has its own abilities and as values are the skill for each ability, I want to print them in desecending order by total skill, this is where I am at the moment:

for (let element in gladiators){ 
        console.log(`${element}: ${Object.values(gladiators[element]).map(Number).reduce((a, b) => a + b, 0)} skill`);
        for (let el in gladiators[element]){
            console.log(`- ${el} <!> ${gladiators[element][el]}`)
        }
    }

this code prints:

Pesho: 400 skill
- Duck <!> 400
Gladius: 700 skill
- Heal <!> 200
- Support <!> 250
- Shield <!> 250

I simply want it to print:

Gladius: 700 skill
- Shield <!> 250
- Support <!> 250
- Heal <!> 200
Pesho: 400 skill
- Duck <!> 400

I want the total skill to be in descending order, if its equal, sort in ascending order, the same for each ability the gladiator has. Please suggest me how can I make my question more clear if I have mistakes I read the guide a few times.

Advertisement

Answer

We should be able to use Object.entries and Array.sort to arrange the objects as we wish, then print out the results:

gladiators = {
  Pesho: { Duck: '400' },
  Gladius: { Heal: '200', Support: '250', Shield: '250' }
}

// Get our array of gladiators, add total skill and add sorted abilities array.
let result = Object.entries(gladiators).map(([name, glad]) => { 
    let abilities = Object.entries(glad);
    return { name, Total: abilities.reduce((acc, [k,v]) => acc + Number(v) , 0), abilities: abilities.sort(([k1,v1], [k2,v2]) => v2 - v1) };
});

// Sort the result in descending order by total skill.
result.sort((a,b) => b.Total - a.Total);

// Print out our result.
result.forEach(res => { 
    console.log(`${res.name}: ${res.Total} skill`)
    res.abilities.forEach(([k,v]) => console.log(` - ${k} <!>`,v));
})
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement