Tengo una matriz de objetos matchesScoreResult como esta:
[ { roundId: '397a57f6-c9da-4017-bf98-62d7d48c1da5', teamId: '32305c41-00e8-492a-859c-83c262230e06', score: '7' }, { roundId: '397a57f6-c9da-4017-bf98-62d7d48c1da5', teamId: '1122ef35-8bce-4310-838b-8221228cadc9', score: '18' }, { roundId: 'c91f1a16-df97-4716-bb0d-8589612da704', teamId: '32305c41-00e8-492a-859c-83c262230e06', score: '21' }, { roundId: 'c91f1a16-df97-4716-bb0d-8589612da704', teamId: '1122ef35-8bce-4310-838b-8221228cadc9', score: '19' } ] Este es un arreglo para algunas rounds de un game (como pueden ver, la roundId key se encuentra dos veces igual, porque hay two teams that play in the same round , y el caso es que los same two teams jugaron two different rounds )
Según el roundId y el equipo que ganó, quiero incrementar la variable firstTeamRoundsWon o secondTeamRoundsWon .
Primero obtengo una unique round ids array como esta:
let uniqueRoundIds = [...new Set(matchesScoreResult.map(item => item.roundId))] Basado en esa uniqueRoundIds array , hago las siguientes operaciones:
uniqueRoundIds.map(roundId => matchesScoreResult.filter(teamRound => teamRound.roundId === roundId) .map(round => round.reduce((previousValue, currentValue) => previousValue.score > currentValue.score ? firstTeamRoundsWon++ : secondTeamRoundsWon++)) Mi problema es que aumenta el doble de las firstTeamRoundsWon por el equipo, pero según mis datos, ambas variables deberían ser 1 .
Is there something wrong that I did there?
Estoy abierto a otras formas de resolver esto.
¡Gracias por tu ayuda!
Puede verificar la lógica a continuación con algunos comentarios
const matchesScoreResult = [{ roundId: '397a57f6-c9da-4017-bf98-62d7d48c1da5', teamId: '32305c41-00e8-492a-859c-83c262230e06', score: '7' }, { roundId: '397a57f6-c9da-4017-bf98-62d7d48c1da5', teamId: '1122ef35-8bce-4310-838b-8221228cadc9', score: '18' }, { roundId: 'c91f1a16-df97-4716-bb0d-8589612da704', teamId: '32305c41-00e8-492a-859c-83c262230e06', score: '21' }, { roundId: 'c91f1a16-df97-4716-bb0d-8589612da704', teamId: '1122ef35-8bce-4310-838b-8221228cadc9', score: '19' } ] //grouBy is not available in browsers yet, so we need to have polyfill for it Array.prototype.groupBy = function(key) { return this.reduce(function(current, value) { (current[value[key]] = current[value[key]] || []).push(value); return current; }, {}); }; //group similar rounds to become matches const matches = matchesScoreResult.groupBy('roundId') //find all unquie team ids let teams = [...new Set(matchesScoreResult.map(item => item.team))] const teamScores = teams.reduce((teamData, team) => { //loop through all matches with the first and second round data for (const [firstRound, secondRound] of Object.values(matches)) { //count for the team win the first round if (Number(firstRound.score) > Number(secondRound.score)) { if (!teamData[firstRound.teamId]) { teamData[firstRound.teamId] = 0 } teamData[firstRound.teamId] += 1 } //count for the team win the second round if (Number(firstRound.score) < Number(secondRound.score)) { if (!teamData[secondRound.teamId]) { teamData[secondRound.teamId] = 0 } teamData[secondRound.teamId] += 1 } } return teamData }, {}) //print out all team ids with the counts console.log(teamScores) //convert `teamScores` to your desired values const [firstTeamRoundsWon, secondTeamRoundsWon] = Object.values(teamScores) console.log({ firstTeamRoundsWon, secondTeamRoundsWon })Creo que su problema es con un malentendido de la función de reducción. El valor anterior es lo que regresa de la última iteración que hizo. En este caso, será el valor de firstTeamRoundsWon o secondTeamRoundsWon. Y un number.score devuelve indefinido. La función de reducción está destinada a ser utilizada para tomar una matriz y reducirla a un solo valor de alguna manera.
No creo que usar firstTeamRoundsWon y secondTeamRoundsWon sea la mejor manera de realizar un seguimiento de cuántas veces ha ganado cada vez, ya que parece depender mucho del orden de la matriz.
En su lugar, sugeriría un objeto cuyas claves sean el ID del equipo y el valor sea la cantidad de veces que han ganado.
const teamWins = {} [...new Set(matchesScoreResult.map(round => round.teamId))].forEach(teamId => teamWins[teamId] = 0) [...new Set(matchesScoreResult.map(round => round.roundId))].forEach(roundId => { // Assuming there will only ever be 2 teams per round const teams = matchesScoreResult.filter(round => round.roundId === roundId) teamWins[teams[teams[0].score > teams[1].score ? 0 : 1].teamID]++ // If teams had a draw here then the second listed team in the array would have a win added. }) console.log(teamWins)por cierto. Debe usar map si desea mutar la matriz a otra forma y forEach si solo desea iterar sobre cada resultado y no le importa que devuelva un valor.