Tally and rank quiz scores
How to fetch and submit this exercise
Once: install the tool and connect your account.
curl -fsSL https://gonomicon.com/install.sh | sh
gonomicon loginEach exercise: download it, edit the file named in the instructions, then submit.
gonomicon fetch fs-week-2/03-02-tally-and-rank-scores
cd 03-02-tally-and-rank-scores
gonomicon submitTally and rank quiz scores
Write one function that totals a list of scores, and another that ranks a list of players by score without disturbing the original list.
Worked example
Here's a similar pair of functions for a community garden's weigh-ins:
function totalYield(weighIns) {
return weighIns.reduce((sum, amount) => sum + amount, 0);
}
const gardens = [
{ gardener: "Lee", yield: 40 },
{ gardener: "Omar", yield: 55 },
{ gardener: "Priya", yield: 32 },
];
function rankGardens(gardens) {
return [...gardens].sort((a, b) => b.yield - a.yield);
}
console.log(totalYield([12, 18, 9, 15]));
console.log(rankGardens(gardens));
console.log(gardens);
54
[
{ gardener: 'Omar', yield: 55 },
{ gardener: 'Lee', yield: 40 },
{ gardener: 'Priya', yield: 32 }
]
[
{ gardener: 'Lee', yield: 40 },
{ gardener: 'Omar', yield: 55 },
{ gardener: 'Priya', yield: 32 }
]
totalYield reduces a plain array of numbers into one sum. rankGardens spreads gardens into a brand-new array first ([...gardens]), then sorts that copy - gardens itself, printed last, keeps its original order.
Your task
Write function totalScore(attempts). attempts is an array of numbers (each one a quiz attempt's score). It returns the sum of all of them using .reduce().
Write function rankPlayers(players). Each player is an object { name, score }. It returns a brand-new array of those same player objects, sorted by score from highest to lowest, without changing the order of the players array that was passed in.
Rules
totalScore([])returns0.rankPlayersreturns a different array object than the one it was given - not the same array, reordered.- The
playersarray passed in keeps its original order after callingrankPlayers- don't sort it in place. - If two or more players are tied on score, they keep their original relative order in the ranked result.
What you'll practice
Using .reduce() to total a list of numbers, and copying an array before sorting it so the original stays exactly as it was.
Run it
gonomicon fetch fs-week-2/03-02-tally-and-rank-scores
cd 03-02-tally-and-rank-scores
gonomicon test
gonomicon submit
Hints
- reduce(...) with a starting value of 0 is the whole of totalScore - no loop needed.
- Sorting a copy, not the original, means making the copy first: [...players].sort(...), not players.sort(...).
- JavaScript's sort is stable, so two players with the same score will already come out in their original relative order once you sort a copy correctly - you don't need to handle ties specially.