Lesson 3 of 8

Sorting without breaking the original

Goal

Careful: sort changes the original

01

Explanation

A common mistake is forgetting that array.sort() changes the array itself and then returns it, so you sort it once and its original order is gone for good.

The fix is to take a copy before sorting, [...products].sort(...), or to use products.toSorted(...) in modern JavaScript.

The compare function returns a number: a negative one means the first item comes before the second, and a positive one means the opposite. For numbers you write (a, b) => a.price - b.price.

02

Your task

Make the two buttons sort the products by price, ascending and descending, while products keeps its original order.

Checks

5 checks
  1. The list shows all four products
  2. "Cheapest first" puts Ruler at the top
  3. "Most expensive first" puts Bag at the top
  4. The whole list is in order, not just the first item
  5. The products array keeps its original order
03

Hints

0/3
index.html
Preview
index.html100%
–/5

Press “Run and check” to grade your code.

5 checks listed under “Your task”.