I have 3 results with the properties teams and medals: Gold, bronze and silver. I need to total the medals by country, that is, add the 3 types of medals and assign the value to each corresponding country.
I can't use neither libraries nor regular expressions.
If you can help me, I appreciate it.
Estos son mis objetos:
0: [{team: 'JOR', medal: 'Gold', total: 1}
1: {team: 'GBR', medal: 'Gold', total: 64}
2: {team: 'USA', medal: 'Gold', total: 139}]
0: [{team: 'JOR', medal: 'Silver', total: 55}
1: {team: 'GBR', medal: 'Silver', total: 28}
2: {team: 'USA', medal: 'Silver', total: 25}]
0: {team: 'JOR', medal: 'Bronze', total: 24}
1: {team: 'GBR', medal: 'Bronze', total: 10}
2: {team: 'USA', medal: 'Bronze', total: 4}
Necesito este resultado
0: {team: 'JOR', totalMedals: 80}
1: {team: 'GBR', totalMedals: 102}
2: {team: 'USA', totalMedals: 168}
This is my code:
const computeData = (datos, medal) => {
const arrayOfNoc = [];
const countriesWonMedals = datos.filter(athletes => athletes.medal === medal)
for (let i = 0; i < countriesWonMedals.length; i++) {
arrayOfNoc.push(countriesWonMedals[i].noc)
}
const teamWithMedals = [];
for (let j = 0; j < arrayOfNoc.length; j++) {
const totalTeamWithMedals = arrayOfNoc[j] + " "+ medal + " " + arrayOfNoc.filter(team => team === arrayOfNoc[j]).length
teamWithMedals.push(totalTeamWithMedals)
}
const eliminatingDuplicateTeams = new Set(teamWithMedals);
let newArrayTeamWithMedals = Array.from(eliminatingDuplicateTeams);
let creatingNewObject = newArrayTeamWithMedals.map(country => ( {
team: country.split(" ")[0],
medal: country.split(" ")[1],
total: Number(country.split(" ")[2])
}))
You can help yourself with an auxiliary structure to save the total results.
On the other hand, since you want to know the total, you can unify all the results of each type of medal in a single array.
Once that is done, you could use a reduce, but to simplify it, I leave you this option:
If you have any questions, you can use the comments.
I hope it can help you
This solution is super vanilla Javascript. It simply uses a list with indexes the name of the country, and adds up the medals of each country.
Then, to maintain the object structure, I convert that list (array) to a list of objects {team:'', totalMedals:0}