Render a sorted table from data, with a header row and a footer row.
What to build
A results table ranked by score.
Requirements
- Keep
results. Render atablewith atheadrow ofthcellsRank,Name,Score, atbodywith onetrper student sorted by score from highest to lowest (equal scores in alphabetical order of name), and atfootrow whose cells areAverage, empty and the average score to one decimal place. - Each
trin the body has the student's id as its key, and shows the rank (1, 2, 3, ...), the name and the score.
Constraints
Do not sort the results array itself.
Example
The first row is "1 Zoya 95"; Arif and Rina, both with 88, come next in alphabetical order; the footer shows "Average 82.6".
Why it works
Sorting a copy keeps the data untouched, the comparison falls back to the name for equal scores, and the rank comes from the position in the sorted array rather than from the data.
Hints
Hint 1
Sort a copy by score (highest first), then by name; the rank is the position plus one.
Hint 2
The average needs one decimal: (total / count).toFixed(1).
Solution
Show one correct solution (try it yourself first)
const results = [
{ id: 1, name: "Rina", score: 88 },
{ id: 2, name: "Zoya", score: 95 },
{ id: 3, name: "Arif", score: 88 },
{ id: 4, name: "Bilal", score: 70 },
{ id: 5, name: "Omar", score: 72 },
];
export default function App() {
const ranked = [...results].sort((a, b) => b.score - a.score || a.name.localeCompare(b.name));
const average = results.reduce((sum, r) => sum + r.score, 0) / results.length;
return (
<table>
<thead>
<tr>
<th>Rank</th>
<th>Name</th>
<th>Score</th>
</tr>
</thead>
<tbody>
{ranked.map((r, i) => (
<tr key={r.id}>
<td>{i + 1}</td>
<td>{r.name}</td>
<td>{r.score}</td>
</tr>
))}
</tbody>
<tfoot>
<tr>
<td>Average</td>
<td></td>
<td>{average.toFixed(1)}</td>
</tr>
</tfoot>
</table>
);
}