Course outline · 0% complete

0/29 lessons0%

Course overview →

Copying, sorting, and slicing

lesson 4-4 · ~10 min · 13/29

Sorting has a trap, copying has a rule

Two array jobs appear in almost every feature — show items in order, and work on a copy without wrecking the original — and JavaScript has a sharp edge in each. Meeting both now is cheaper than meeting them in a bug report.

sort() compares items as text by default. The method was designed to work on arrays of anything, so with no instructions it converts every item to a string and orders alphabetically. For numbers that is wrong: [10, 9, 80].sort() gives [10, 80, 9], because the text "10" sorts before "80", which sorts before "9". The fix is a compare function, an arrow that tells sort how to order any two items: a negative result means a goes first, a positive result means b goes first. So (a, b) => a - b sorts numbers ascending, and (a, b) => b - a sorts descending.

sort() also rearranges the array in place — the original order is gone afterward. When you still need the original, copy first:

  • xs.slice(start, end) returns a new array holding that piece of xs (the job Python did with xs[start:end]). With no arguments, xs.slice() copies the whole array.
  • [...xs] is the spread syntax: the three dots pour every item of xs into a fresh array literal. [...xs].sort(...) is the standard "sorted copy" idiom you will read everywhere.

Code exercise · javascript

Run it. The first sort is the trap: numbers ordered as text. The second passes a compare function. slice hands back a piece, and the last line proves nums itself never changed (both sorts ran on spread copies).

Sorting objects by a property

Real lists are arrays of objects (users, products, scores), and the compare function is where you name the property that decides the order:

const products = [
  { name: "mouse", price: 25 },
  { name: "monitor", price: 180 },
  { name: "cable", price: 8 }
];

const byPrice = [...products].sort((a, b) => a.price - b.price);
// cable, mouse, monitor

The pattern is always the same: spread-copy, then a.<property> - b.<property> for ascending numbers. For text properties use a.name.localeCompare(b.name), a string method that answers negative/zero/positive the way sort expects, alphabetically.

Code exercise · javascript

Your turn. Sort the scores from highest to lowest WITHOUT changing the original array. Print three lines: the sorted array, Top score: <n> using a template literal, and the original array to prove it survived.

Quiz

What does [1, 5, 10].sort() return when no compare function is passed?