I have this object:
JavaScript
x
5
1
gladiators = {
2
Pesho: { Duck: '400' },
3
Gladius: { Heal: '200', Support: '250', Shield: '250' }
4
}
5
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:
JavaScript
1
7
1
for (let element in gladiators){
2
console.log(`${element}: ${Object.values(gladiators[element]).map(Number).reduce((a, b) => a + b, 0)} skill`);
3
for (let el in gladiators[element]){
4
console.log(`- ${el} <!> ${gladiators[element][el]}`)
5
}
6
}
7
this code prints:
JavaScript
1
7
1
Pesho: 400 skill
2
- Duck <!> 400
3
Gladius: 700 skill
4
- Heal <!> 200
5
- Support <!> 250
6
- Shield <!> 250
7
I simply want it to print:
JavaScript
1
8
1
Gladius: 700 skill
2
- Shield <!> 250
3
- Support <!> 250
4
- Heal <!> 200
5
Pesho: 400 skill
6
- Duck <!> 400
7
8
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:
JavaScript
1
19
19
1
gladiators = {
2
Pesho: { Duck: '400' },
3
Gladius: { Heal: '200', Support: '250', Shield: '250' }
4
}
5
6
// Get our array of gladiators, add total skill and add sorted abilities array.
7
let result = Object.entries(gladiators).map(([name, glad]) => {
8
let abilities = Object.entries(glad);
9
return { name, Total: abilities.reduce((acc, [k,v]) => acc + Number(v) , 0), abilities: abilities.sort(([k1,v1], [k2,v2]) => v2 - v1) };
10
});
11
12
// Sort the result in descending order by total skill.
13
result.sort((a,b) => b.Total - a.Total);
14
15
// Print out our result.
16
result.forEach(res => {
17
console.log(`${res.name}: ${res.Total} skill`)
18
res.abilities.forEach(([k,v]) => console.log(` - ${k} <!>`,v));
19
})