TL ; DR:
To sort by your own rule, give sort a compare function. It gets two items, a and b. A negative result puts a first.
let nums = [25, 13, 5, 41, 33];
nums.sort((a, b) => {
if (a % 10 !== b % 10) {
return a % 10 - b % 10;
}
return a - b;
});
// [41, 13, 33, 5, 25]
let scores = [70, 95, 82];
scores.sort((a, b) => b - a);
// [95, 82, 70]
Full lesson:
You met sort() in the Shopping Cart project. It sorted text from A to Z. Sometimes you need another order. The shortest word may have to come first, or the highest score.
Watch out with numbers. A plain sort() compares them as text. So [10, 9, 1].sort() gives [1, 10, 9].
To sort by your own rule, give sort a compare function. The function (a, b) => a - b is written in one line. It has no name. It gets two values, a and b, and returns a - b.
The sort method calls it on two items at a time. The result says which one goes first.
- A negative number puts
afirst. - A positive number puts
bfirst. - Zero means they are equal.
Some rules you will use often:
- Low to high:
(a, b) => a - b. - High to low:
(a, b) => b - a. - Shortest first:
(a, b) => a.length - b.length.
For two rules, the function needs a body in braces. Check the first rule. Use the second one only on a tie, as the if above does.
Above, the first rule compares the last digits, a % 10 and b % 10. Numbers with the same last digit then go from small to large.
The localeCompare method compares two strings. It gives a negative number when a comes first from A to Z.
The sort method changes the array itself. To keep the original, sort a copy made with words.slice().
Your task
A pet shop sells toys. Their prices are in prices. Sort prices from high to low.
The shop's pets are in names. Sort names by their last letter, in alphabetical order. Names with the same last letter go from A to Z.
The code already prints both, one item per line.
Expected output:
30
12
8
5
Bella
Luna
Bo
Coco
Max
RexFree plan: 30 tutor messages. PRO is unlimited.
