Skip to the content

Sorting like at work

JavaScript · Unit 22: Searching and sorting

In a real job nobody writes selection sort or merge sort by hand: sort and toSorted ship with the language, tuned by a lot of people over years.

What you do write is the comparator. And if you give it a name, you can reuse it on every list you want.

const smallFirst = (a, b) => a - b;
const ns = [40, 10, 30];
const o = ns.toSorted(smallFirst);
console.log(o, ns);

Prints

[ 10, 30, 40 ] [ 40, 10, 30 ]

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

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

  1. 1. Predict the output

    flipped uses the comparator next to it, with the arguments swapped. What does it print?

  2. 2. Complete the code

    Complete it so that, on equal points, whoever has fewer fouls comes first.

  3. 3. Predict the output

    The tiebreak is alphabetical. What does it print?

  4. 4. Multiple choice

    This comparator is wrong. Why?

  5. 5. Find the bug

    The prices should come out from smallest to largest, that is [ 9, 10, 100 ]. Which line has the error?

  6. 6. Predict the output

    Two people tie on points and the comparator only looks at points. What does it print?

  7. 7. Put the lines in order

    Put in order the function that returns the names from most points to fewest, without shuffling the list it receives.

  8. 8. Find the case that fails

    best(js) returns the name of whoever has the most points, or "nobody" if the list is empty. On a tie, whoever came first wins. Which call does it fail on?

  9. 9. Multiple choice

    Now that you've written your own sorts, when is it worth using them in a real program?

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 →