I’m creating a tournament bracket and the team data is stored in an array like this:
tourneyTeamsCondensed = {
"name": "Team1","wins": "2","losses": "4",
"name": "Team2","wins": "3","losses": "3",
"name": "Team3","wins": "3","losses": "4",
"name": "Team4","wins": "4","losses": "1"};
For the standings, I’d like to store them in a new array, sorted by highest "wins" to lowest, then sorting by lowest to highest "losses" as a tiebreaker. The result should like this:
standingsTeams = {
"name": "Team4","wins": "4","losses": "1",
"name": "Team2","wins": "3","losses": "3",
"name": "Team3","wins": "3","losses": "4",
"name": "Team1","wins": "2","losses": "4"};
How can I accomplish this?
Here’s what I tried:
// Sorting tourneyTeamsCondensed from most wins to least, outputting into standingsTeams
for (var i = 0; i < tourneyTeamsCondensed.length; i++) {
var insertCheck = false;
for (var j = 0; j < standingsTeams.length; j++) {
if (tourneyTeamsCondensed[i].wins > standingsTeams[j].wins ||
(tourneyTeamsCondensed[i].wins === standingsTeams[j].wins &&
tourneyTeamsCondensed[i].losses < standingsTeams[j].losses)) {
insertCheck = true;
standingsTeams.splice(j, 0, tourneyTeamsCondensed[i]);
break;
}
}
if (!insertCheck) {
standingsTeams.push(tourneyTeamsCondensed[i]);
}
}
console.log(standingsTeams)
I had this functionality working previously, but using tourneyTeams instead of tourneyTeamsCondensed. tourneyTeamsCondensed is tourneyTeams, but with wins and losses summed, based on a common "name" attribute. Aside from replacing instances of tourneyTeams with tourneyTeamsCondensed, I changed nothing.
Console logging tourneyTeamsCondensed shows that it’s working as intended, so that shouldn’t be the problem.
Console logging standingsTeams results in an empty array.
2
Answers
First of all, it is important to mention that the original format of your JSON data is not quite valid because all fields in that object are repeated multiple times. Probably, you wanted it to be an array of objects. If this is the case, you can sort objects in the array in the following way:
You can notice that since wins and losses are stored as strings in the initial JSON, I had to parse them during sorting. This is a quite bad approach from performance perspective and to address it, I would suggest to extract parsing into a separate step before sorting, like so:
Now sorting looks nice and tidy 🙂
Please let me know if this helps.