Skip to the content

Project: top three

JavaScript · Unit 22: Searching and sorting

A tournament in the app stores one result per player: name, points and the seconds they took.

The table runs from most points to fewest and, if two tie on points, whoever took less time goes first. Two rules, one comparator.

const js = [
  { n: "Ana", pts: 9, secs: 50 },
  { n: "Leo", pts: 9, secs: 40 },
];
const cmp = (a, b) =>
  b.pts - a.pts || a.secs - b.secs;
const o = js.toSorted(cmp);
console.log(o.map((j) => j.n));

Prints

[ 'Leo', 'Ana' ]

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Complete the code

    Complete the tiebreak: on equal points, whoever took fewer seconds comes first.

  2. 2. Write the code

    Write table(js): it returns a new array with the players sorted from most points to fewest and, on equal points, from fewest seconds to most. The list you receive stays untouched. The check function below is ready and returns the names in order together with the name of the first player in the original list.

  3. 3. Write the code

    Now the podium. Write top3(js): it returns an array with the names of the first three in the table, in order. If there are fewer than three players, return the ones there are; with an empty list, an empty array. The table function is already written below: use it.

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →