Code Lab is in development. New lessons and improvements are on the way. Progress can be deleted.
Loading…
Code Lab is in development. New lessons and improvements are on the way. Progress can be deleted.
Loading…
Code Lab is in development. New lessons and improvements are on the way. Progress can be deleted.
JAVASCRIPT TEXT / CHAPTER 03 / Learn / LESSON 07
Seventh class. sort() without a comparator orders as strings: [10, 2, 1] → "1","10","2" — wrong for amounts.
For numbers pass a comparator: (a, b) => a - b (ascending) or b - a (descending). sort mutates the array in place.
Mini example:
const amounts = [40, 12, 25]; amounts.sort((a, b) => a - b); console.log(amounts);
Common mistake: amounts.sort() with no comparator for numbers; or expecting a new array without mutation (sort returns the same array).
Without a comparator, sort is lexicographic.
DATA STANDBY
›