Sorting in depth
JavaScript · Unit 8: More on arrays
- Full plan
- JavaScript
- 10 exercises
A refresher: sort takes a comparator (a, b) => a - b. If it gives a negative number, a goes first; if positive, it goes after; if 0, they stay as they were.
And sort sorts the array itself: it doesn't make a copy.
const nums = [30, 5, 12];
nums.sort((a, b) => a - b);
console.log(nums);Prints
[ 5, 12, 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. Predict the output
What does this code print?
2. Multiple choice
The
sortcomparator getsaandband returns a number. If it returns a negative number, what happens?3. Predict the output
What does this code print?
4. Complete the code
Complete it to sort from the highest grade to the lowest.
5. Find the bug
This program should print the items from cheapest to most expensive. Which line has the error?
6. Complete the code
Complete it to sort the cities in alphabetical order.
7. Predict the output
This sorts by length and, if there's a tie, in alphabetical order. What does it print?
8. Put the lines in order
Order the function that sorts the results of a race: first whoever took the fewest minutes and, if they're tied, whoever is younger.
9. Multiple choice
What does this code do?
10. Predict the output
The function looks for the highest score. What does it print?
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.