🟨 JavaScript G10 · session 1 of 12 · 60 minutes · free

Array sorting and mapping

An arcade needs its leaderboard in order: players A to Z, scores from highest to lowest, every score labelled. Today you make arrays sort themselves, flip them, fix the famous number-sorting trap and build new arrays with map().

🎯 Practice mode⚔️ Boss battle🖨 Print a worksheet
Illustration of a cute pastel robot dancing
Illustration: andremsdesign / Pixabay

A complete lesson · 60 minutes

Teach it, see it, practise it, all on this page.

Open this page with your learner and work down it, or press Teach this lesson to go through it one step at a time on a big screen. Every section has something to do.

See the teacher's plan
  1. Warm-up4 min
  2. sort() and reverse()12 min
  3. Sorting numbers with a compare function12 min
  4. map()12 min
  5. Leaderboard printout6 min
  6. Snack shop shelf5 min
  7. Class register cleanup4 min
  8. Quiz4 min
  9. Set the after-class project1 min

By the end you can

  • Put text in A to Z order with sort(), and explain why capital letters come first
  • Flip an array with reverse(), and combine sort() and reverse() for Z to A
  • Sort numbers by value with a compare function: a - b and b - a
  • Make a new array with map() and explain why the original stays the same

Before you start

  • Variables with var and console.log()
  • Arrays: [ ], indexes, push(), pop() and join()
  • Writing a function that returns a value

Have ready

  • This page (JavaScript runs in the browser)
  • The interactive lesson: learnfun.in/learn/javascript-sort-map (Arcade Leaderboard builder)
  • Paper to predict outputs before running

Grade 10 · ages 14 to 16 · after an introduction to JavaScript

Warm-up · think first

Your arcade's scores are [480, 95, 1200, 300, 65]. In a high-score table, which comes first? Now imagine sorting them as words in a dictionary: which comes first then?

Show the answer

By value, 1200 comes first (highest score). As words, 1200 also starts with 1, but 300 would come before 480, and 95 would be last because 9 comes after 6. JavaScript's sort() does the dictionary version unless you tell it how to compare numbers.

Teacher tip: Collect both answers, then promise: by the end of today the computer will get both right.

More warm-ups for every class →

Three levels, like a real engineer

Use it. Tweak it. Build it.

First use what the lesson shows exactly as it is, then change one key thing and see what happens, then make your own.

  1. 🔒

    Level 1 · Use it

    Run it as it is

    Run this exact code: let fruits = ['banana','Apple','cherry']; fruits.sort(); console.log(fruits); and notice the order and which letter is capital.

  2. 🔧

    Level 2 · Tweak it

    Change one value

    In the same fruits code, change 'Apple' to 'apple' and add 'date'. Predict the new order, then run it.

  3. 🛠️

    Level 3 · Build it

    Sort it, map it

    Make your own array of four numbers. Use map(n => n * 2) to double them, then sort((a, b) => a - b) to order them. Print the original after each step: which method changed it, and which made a new array?

🗺️ Play the Lesson QuestThree worlds, one for each level, with short stages that bring back what you miss.

Part 1 of 3 · learn, see, practise

sort() and reverse(): putting text in order

Welcome to the arcade's back office. Five players signed up today and the leaderboard shows them in the order they arrived. Let's make the array tidy itself.

sort() arranges an array's items in order and changes the original array. For text that means A to Z: it compares the first letters, and if they match, the next ones.

It compares letter codes, and every capital letter (A to Z are 65 to 90) has a smaller code than every small letter (a to z are 97 to 122). So "Zara" comes before "ben".

reverse() flips the array's current order: the last item becomes the first. It does not sort, so for Z to A call sort() first and then reverse().

Remember!
  • sort() changes the original array.
  • Capital letters come before small letters.
  • Z to A = sort() then reverse().

🧑‍🏫 Teacher: type this live with the class

Line up the players

  1. var players = ["Mira", "Dev", "Zoya", "Kabir", "Aria"];

    Five players in the order they joined. Ask: who should be first, A to Z?

  2. players.sort();

    One method call. It changes players itself.

  3. console.log(players.join(", "));

    join turns the array into text. Run it: Aria, Dev, Kabir, Mira, Zoya.

  4. players.reverse();

    Now flip the sorted list.

  5. console.log(players.join(", "));

    Z to A. Ask: what would reverse() have done before sort()?

Type here

▶ Output

(nothing is printed)

📦 Memory boxes

No variables yet
Example: run it, then change it

▶ Output

Ben, Zara, ben, zoe
Zoya, Dev, Mira

📦 Memory boxes

names[ 'Ben', 'Zara', 'ben', 'zoe' ]arraymixed[ 'Zoya', 'Dev', 'Mira' ]array

Predict both lines before running. The first shows capitals first; the second shows that reverse() only flips, it doesn't sort.

Practise it

Start with the warm-up and go as far as you can. The stretch questions are meant to be hard.

Warm-up

1.1 Sort the fruits A to Z and print them joined with ", ".

Task 1.1

▶ Output

(nothing is printed)

📦 Memory boxes

fruits[ 'mango', 'apple', 'kiwi', 'banana' ]array
🧑‍🏫 Model answer (for the teacher)

Teacher eyes only: hide the answers before you share your screen.

The answer green = the 2 lines the student writes

var fruits = ["mango", "apple", "kiwi", "banana"];fruits.sort();console.log(fruits.join(", "));

What it prints

apple, banana, kiwi, mango

What ✓ Check looks for

  • it prints exactly:
    apple, banana, kiwi, mango
  • In the code: Use fruits.sort().
Warm-up

1.2 Print the cities Z to A: sort them, then reverse them.

Task 1.2

▶ Output

(nothing is printed)

📦 Memory boxes

cities[ 'Pune', 'Agra', 'Delhi', 'Surat' ]array
🧑‍🏫 Model answer (for the teacher)

Teacher eyes only: hide the answers before you share your screen.

The answer green = the 3 lines the student writes

var cities = ["Pune", "Agra", "Delhi", "Surat"];cities.sort();cities.reverse();console.log(cities.join(", "));

What it prints

Surat, Pune, Delhi, Agra

What ✓ Check looks for

  • it prints exactly:
    Surat, Pune, Delhi, Agra
  • In the code: Use cities.reverse() after sort().
Core

1.3 Sort the teams A to Z, then print the first team and how many teams there are, like: Aces 4

Task 1.3

▶ Output

(nothing is printed)

📦 Memory boxes

teams[ 'Tigers', 'Aces', 'Rockets', 'Owls' ]array
🧑‍🏫 Model answer (for the teacher)

Teacher eyes only: hide the answers before you share your screen.

The answer green = the 2 lines the student writes

var teams = ["Tigers", "Aces", "Rockets", "Owls"];teams.sort();console.log(teams[0] + " " + teams.length);

What it prints

Aces 4

What ✓ Check looks for

  • it prints exactly:
    Aces 4
  • In the code: Sort the teams first.
Core

1.4 Print the playlist backwards (last song first) without sorting it.

Task 1.4

▶ Output

(nothing is printed)

📦 Memory boxes

songs[ 'Intro', 'Rise', 'Glow', 'Outro' ]array
🧑‍🏫 Model answer (for the teacher)

Teacher eyes only: hide the answers before you share your screen.

The answer green = the 2 lines the student writes

var songs = ["Intro", "Rise", "Glow", "Outro"];songs.reverse();console.log(songs.join(", "));

What it prints

Outro, Glow, Rise, Intro

What ✓ Check looks for

  • it prints exactly:
    Outro, Glow, Rise, Intro
  • In the code: Use songs.reverse().
  • In the code: Don't sort: only flip the order.
Stretch 🔥

1.5 Capitals spoil the order. Make every name lowercase with a for loop, then sort and print them.

Task 1.5

▶ Output

(nothing is printed)

📦 Memory boxes

names[ 'banana', 'Cherry', 'apple', 'Date' ]array
🧑‍🏫 Model answer (for the teacher)

Teacher eyes only: hide the answers before you share your screen.

The answer green = the 5 lines the student writes

var names = ["banana", "Cherry", "apple", "Date"];for (var i = 0; i < names.length; i++) {  names[i] = names[i].toLowerCase();}names.sort();console.log(names.join(", "));

What it prints

apple, banana, cherry, date

What ✓ Check looks for

  • it prints exactly:
    apple, banana, cherry, date
  • In the code: Use toLowerCase() on every name.
Stretch 🔥

1.6 Print both orders on two lines: A to Z: … and Z to A: …

Task 1.6

▶ Output

(nothing is printed)

📦 Memory boxes

words[ 'moon', 'star', 'comet', 'sun' ]array
🧑‍🏫 Model answer (for the teacher)

Teacher eyes only: hide the answers before you share your screen.

The answer green = the 4 lines the student writes

var words = ["moon", "star", "comet", "sun"];words.sort();console.log("A to Z: " + words.join(", "));words.reverse();console.log("Z to A: " + words.join(", "));

What it prints

A to Z: comet, moon, star, sun
Z to A: sun, star, moon, comet

What ✓ Check looks for

  • it prints exactly:
    A to Z: comet, moon, star, sun
    Z to A: sun, star, moon, comet
  • In the code: Use reverse() for the second line.

Part 2 of 3 · learn, see, practise

Sorting numbers with a compare function

The scores look wrong after sort(): 1200, 300, 480, 65, 95. The arcade manager is not happy. Time to tell sort() how to compare numbers.

With no compare function, sort() turns every item into text and compares them like words. "1200" starts with 1 and "300" with 3, so 1200 comes first, and 95 comes last because 9 is the biggest first digit.

Give sort() a compare function: function (a, b) { return a - b; }. sort() calls it with two items. A negative answer puts a first, a positive answer puts b first, zero keeps them as they are.

a - b sorts from lowest to highest. b - a sorts from highest to lowest, which is what a high-score table needs. The arrow form (a, b) => a - b does the same.

Remember!
  • Numbers need a compare function.
  • a - b: low to high. b - a: high to low.
  • Negative: a first. Positive: b first.

🧑‍🏫 Teacher: type this live with the class

Fix the scoreboard

  1. var scores = [480, 95, 1200, 300, 65];

    The arcade's scores. Ask: what should the highest-first order be?

  2. scores.sort();

    The trap: no compare function.

  3. console.log(scores.join(", "));

    Run it: 1200, 300, 480, 65, 95. Ask why 95 is last.

  4. scores.sort(function (a, b) { return a - b; });

    Now sort by value: the smaller number first.

  5. console.log(scores.join(", "));

    65, 95, 300, 480, 1200. Then change it to b - a and run again.

Type here

▶ Output

(nothing is printed)

📦 Memory boxes

No variables yet
Example: run it, then change it

▶ Output

As text: 1200, 300, 480, 65, 95
Lowest first: 65, 95, 300, 480, 1200
Highest first: 1200, 480, 300, 95, 65

📦 Memory boxes

scores[ 1200, 480, 300, 95, 65 ]array

The third sort uses an arrow function: (a, b) => b - a means the same as function (a, b) { return b - a; }.

Practise it

Start with the warm-up and go as far as you can. The stretch questions are meant to be hard.

Warm-up

2.1 Sort the ages from youngest to oldest and print them.

Task 2.1

▶ Output

(nothing is printed)

📦 Memory boxes

ages[ 15, 9, 12, 40, 7 ]array
🧑‍🏫 Model answer (for the teacher)

Teacher eyes only: hide the answers before you share your screen.

The answer green = the 2 lines the student writes

var ages = [15, 9, 12, 40, 7];ages.sort(function (a, b) { return a - b; });console.log(ages.join(", "));

What it prints

7, 9, 12, 15, 40

What ✓ Check looks for

  • it prints exactly:
    7, 9, 12, 15, 40
  • In the code: Use a compare function that returns a - b.
Warm-up

2.2 Sort the prices from most to least expensive and print them.

Task 2.2

▶ Output

(nothing is printed)

📦 Memory boxes

prices[ 250, 99, 1200, 45 ]array
🧑‍🏫 Model answer (for the teacher)

Teacher eyes only: hide the answers before you share your screen.

The answer green = the 2 lines the student writes

var prices = [250, 99, 1200, 45];prices.sort(function (a, b) { return b - a; });console.log(prices.join(", "));

What it prints

1200, 250, 99, 45

What ✓ Check looks for

  • it prints exactly:
    1200, 250, 99, 45
  • In the code: Use a compare function that returns b - a.
Core

2.3 Prove the trap: print the scores sorted without a compare function, then with a - b, on two lines.

Task 2.3

▶ Output

(nothing is printed)

📦 Memory boxes

scores[ 100, 25, 3, 1000 ]array
🧑‍🏫 Model answer (for the teacher)

Teacher eyes only: hide the answers before you share your screen.

The answer green = the 4 lines the student writes

var scores = [100, 25, 3, 1000];scores.sort();console.log(scores.join(", "));scores.sort(function (a, b) { return a - b; });console.log(scores.join(", "));

What it prints

100, 1000, 25, 3
3, 25, 100, 1000

What ✓ Check looks for

  • it prints exactly:
    100, 1000, 25, 3
    3, 25, 100, 1000
Core

2.4 Sort the race times (in seconds) and print the fastest and the slowest, like: Fastest: 49 and Slowest: 70.

Task 2.4

▶ Output

(nothing is printed)

📦 Memory boxes

times[ 58, 61, 49, 70, 52 ]array
🧑‍🏫 Model answer (for the teacher)

Teacher eyes only: hide the answers before you share your screen.

The answer green = the 3 lines the student writes

var times = [58, 61, 49, 70, 52];times.sort(function (a, b) { return a - b; });console.log("Fastest: " + times[0]);console.log("Slowest: " + times[times.length - 1]);

What it prints

Fastest: 49
Slowest: 70

What ✓ Check looks for

  • it prints exactly:
    Fastest: 49
    Slowest: 70
  • In the code: Sort with a - b first.
Stretch 🔥

2.5 Top 3: sort the scores highest first and print only the top three with slice(0, 3).

Task 2.5

▶ Output

(nothing is printed)

📦 Memory boxes

scores[ 480, 95, 1200, 300, 65 ]array
🧑‍🏫 Model answer (for the teacher)

Teacher eyes only: hide the answers before you share your screen.

The answer green = the 2 lines the student writes

var scores = [480, 95, 1200, 300, 65];scores.sort(function (a, b) { return b - a; });console.log(scores.slice(0, 3).join(", "));

What it prints

1200, 480, 300

What ✓ Check looks for

  • it prints exactly:
    1200, 480, 300
  • In the code: Use slice(0, 3) to keep the first three.
Stretch 🔥

2.6 Sort a copy and keep the original: copy with slice(), sort the copy, then print both.

Task 2.6

▶ Output

(nothing is printed)

📦 Memory boxes

marks[ 5, 3, 9, 1 ]array
🧑‍🏫 Model answer (for the teacher)

Teacher eyes only: hide the answers before you share your screen.

The answer green = the 4 lines the student writes

var marks = [5, 3, 9, 1];var copy = marks.slice();copy.sort(function (a, b) { return a - b; });console.log("Original: " + marks.join(", "));console.log("Sorted: " + copy.join(", "));

What it prints

Original: 5, 3, 9, 1
Sorted: 1, 3, 5, 9

What ✓ Check looks for

  • it prints exactly:
    Original: 5, 3, 9, 1
    Sorted: 1, 3, 5, 9
  • In the code: Copy the array with marks.slice() first.

Part 3 of 3 · learn, see, practise

map(): a new array from every item

The leaderboard should say 480 pts, not just 480. We could type every label by hand, or let map() stamp them all.

map() runs a function on every item of an array and collects what the function returns into a new array: var labelled = scores.map(function (s) { return s + " pts"; });

The original array stays the same. That's the big difference from sort() and reverse(), which change the array they are called on. Keep the result in a new variable.

The function must return something. Without return, every new item is undefined. The function can also receive the item's position: map(function (s, i) { … }) gives 0, 1, 2 …

Remember!
  • map() makes a NEW array.
  • The original stays the same.
  • Don't forget return.

🧑‍🏫 Teacher: type this live with the class

Stamp the labels

  1. var scores = [480, 95, 1200];

    Three scores. Ask: how would you add pts to each by hand?

  2. var labelled = scores.map(function (s) {

    map() will call this function once for every score.

  3. return s + " pts";

    Whatever we return becomes the new item.

  4. });

    Close the function and the map() call.

  5. console.log(labelled.join(", "));

    Run it: 480 pts, 95 pts, 1200 pts.

  6. console.log(scores.join(", "));

    The original is unchanged. Ask: what happens if we delete return?

Type here

▶ Output

(nothing is printed)

📦 Memory boxes

No variables yet
Example: run it, then change it

▶ Output

480 pts, 95 pts, 1200 pts
480, 95, 1200
960, 190, 2400
1. 480 | 2. 95 | 3. 1200

📦 Memory boxes

scores[ 480, 95, 1200 ]arraylabelled[ '480 pts', '95 pts', '1200 pts' ]arraydoubled[ 960, 190, 2400 ]arrayplaces[ '1. 480', '2. 95', '3. 1200' ]array

Delete return from the first map and run again: every label becomes empty (undefined).

Practise it

Start with the warm-up and go as far as you can. The stretch questions are meant to be hard.

Warm-up

3.1 Double every number with map() and print the new array.

Task 3.1

▶ Output

(nothing is printed)

📦 Memory boxes

nums[ 2, 5, 10 ]array
🧑‍🏫 Model answer (for the teacher)

Teacher eyes only: hide the answers before you share your screen.

The answer green = the 2 lines the student writes

var nums = [2, 5, 10];var doubled = nums.map(function (n) { return n * 2; });console.log(doubled.join(", "));

What it prints

4, 10, 20

What ✓ Check looks for

  • it prints exactly:
    4, 10, 20
  • In the code: Use nums.map().
Warm-up

3.2 Add " coins" to every number with map() and print the labels.

Task 3.2

▶ Output

(nothing is printed)

📦 Memory boxes

coins[ 10, 25, 5 ]array
🧑‍🏫 Model answer (for the teacher)

Teacher eyes only: hide the answers before you share your screen.

The answer green = the 2 lines the student writes

var coins = [10, 25, 5];var labels = coins.map(function (c) { return c + " coins"; });console.log(labels.join(", "));

What it prints

10 coins, 25 coins, 5 coins

What ✓ Check looks for

  • it prints exactly:
    10 coins, 25 coins, 5 coins
  • In the code: Use coins.map().
Core

3.3 Make every name shout: map each name to the name in capitals with "!" after it.

Task 3.3

▶ Output

(nothing is printed)

📦 Memory boxes

names[ 'mira', 'dev', 'aria' ]array
🧑‍🏫 Model answer (for the teacher)

Teacher eyes only: hide the answers before you share your screen.

The answer green = the 2 lines the student writes

var names = ["mira", "dev", "aria"];var loud = names.map(function (n) { return n.toUpperCase() + "!"; });console.log(loud.join(", "));

What it prints

MIRA!, DEV!, ARIA!

What ✓ Check looks for

  • it prints exactly:
    MIRA!, DEV!, ARIA!
  • In the code: Use name.toUpperCase().
Core

3.4 Show that map() keeps the original: double the prices, then print the new array and then the original.

Task 3.4

▶ Output

(nothing is printed)

📦 Memory boxes

prices[ 100, 200, 350 ]array
🧑‍🏫 Model answer (for the teacher)

Teacher eyes only: hide the answers before you share your screen.

The answer green = the 3 lines the student writes

var prices = [100, 200, 350];var doubled = prices.map(function (p) { return p * 2; });console.log(doubled.join(", "));console.log(prices.join(", "));

What it prints

200, 400, 700
100, 200, 350

What ✓ Check looks for

  • it prints exactly:
    200, 400, 700
    100, 200, 350
  • In the code: Use prices.map().
Stretch 🔥

3.5 Sort the scores highest first, then use map() with the position to label each one, like 1. 1200

Task 3.5

▶ Output

(nothing is printed)

📦 Memory boxes

scores[ 480, 95, 1200, 300, 65 ]array
🧑‍🏫 Model answer (for the teacher)

Teacher eyes only: hide the answers before you share your screen.

The answer green = the 3 lines the student writes

var scores = [480, 95, 1200, 300, 65];scores.sort(function (a, b) { return b - a; });var places = scores.map(function (s, i) { return (i + 1) + ". " + s; });console.log(places.join(", "));

What it prints

1. 1200, 2. 480, 3. 300, 4. 95, 5. 65

What ✓ Check looks for

  • it prints exactly:
    1. 1200, 2. 480, 3. 300, 4. 95, 5. 65
  • In the code: Give the function two inputs: the score and its position.
Stretch 🔥

3.6 Festival sale: take ₹10 off every price with map(), then print the new prices with ₹ in front, cheapest first.

Task 3.6

▶ Output

(nothing is printed)

📦 Memory boxes

prices[ 120, 30, 90, 60 ]array
🧑‍🏫 Model answer (for the teacher)

Teacher eyes only: hide the answers before you share your screen.

The answer green = the 4 lines the student writes

var prices = [120, 30, 90, 60];var sale = prices.map(function (p) { return p - 10; });sale.sort(function (a, b) { return a - b; });var shown = sale.map(function (p) { return "₹" + p; });console.log(shown.join(", "));

What it prints

₹20, ₹50, ₹80, ₹110

What ✓ Check looks for

  • it prints exactly:
    ₹20, ₹50, ₹80, ₹110
  • In the code: Use map() for the discount and the ₹ labels.

Watch out

Common mistakes

Sorting numbers with plain sort()

The numbers are compared as text, so 1200 comes before 300. Give sort() a compare function: a - b or b - a.

Calling reverse() and expecting Z to A

reverse() only flips the current order. Call sort() first.

Forgetting return inside map()

Every new item becomes undefined. The function must return the new value.

Expecting map() to change the original

map() makes a new array. Keep it in a variable, like var labelled = scores.map(…).

Forgetting that sort() changes the array

After sort() the original order is gone. Copy first with slice() if you still need it.

Class activity 1 of 3

Leaderboard printout

Print the arcade's leaderboard four ways. When it works it prints:
A to Z: Aria, Dev, Kabir, Mira, Zoya
Z to A: Zoya, Mira, Kabir, Dev, Aria
Top scores: 1200, 480, 300, 95, 65
Labels: 1200 pts, 480 pts, 300 pts, 95 pts, 65 pts

  1. Sort the players and print them A to Z.
  2. Reverse them and print Z to A.
  3. Sort the scores highest first with a compare function and print them.
  4. Use map() to add " pts" to every score and print the labels.
Your code

▶ Output

(nothing is printed)

📦 Memory boxes

players[ 'Mira', 'Dev', 'Zoya', 'Kabir', 'Aria' ]arrayscores[ 480, 95, 1200, 300, 65 ]array
Hint

Step 2 works because the players are already A to Z from step 1: reverse() just flips that.

🧑‍🏫 Model answer (for the teacher)

Teacher eyes only: hide the answers before you share your screen.

The answer green = the 8 lines the student writes

// ===== Leaderboard printout =====var players = ["Mira", "Dev", "Zoya", "Kabir", "Aria"];var scores = [480, 95, 1200, 300, 65]; players.sort();console.log("A to Z: " + players.join(", ")); players.reverse();console.log("Z to A: " + players.join(", ")); scores.sort(function (a, b) { return b - a; });console.log("Top scores: " + scores.join(", ")); var labels = scores.map(function (s) { return s + " pts"; });console.log("Labels: " + labels.join(", "));

What it prints

A to Z: Aria, Dev, Kabir, Mira, Zoya
Z to A: Zoya, Mira, Kabir, Dev, Aria
Top scores: 1200, 480, 300, 95, 65
Labels: 1200 pts, 480 pts, 300 pts, 95 pts, 65 pts

What ✓ Check looks for

  • it prints exactly:
    A to Z: Aria, Dev, Kabir, Mira, Zoya
    Z to A: Zoya, Mira, Kabir, Dev, Aria
    Top scores: 1200, 480, 300, 95, 65
    Labels: 1200 pts, 480 pts, 300 pts, 95 pts, 65 pts
  • In the code: Step 3: sort the scores with return b - a.
  • In the code: Step 4: make the labels with scores.map().

If they're stuck, say

Step 2 works because the players are already A to Z from step 1: reverse() just flips that.

Class activity 2 of 3

Snack shop shelf

The snack shop wants its menu A to Z and its prices cheapest first, with ₹ in front. When it works it prints:
Menu: Burger, Idli, Juice, Pizza, Samosa
Cheapest first: ₹30, ₹40, ₹60, ₹90, ₹120

  1. Sort the snacks A to Z and print the menu.
  2. Sort the prices from cheapest to dearest with a compare function.
  3. Use map() to put ₹ in front of every price, then print them.
Your code

▶ Output

(nothing is printed)

📦 Memory boxes

snacks[ 'Samosa', 'Juice', 'Pizza', 'Idli', 'Burger' ]arrayprices[ 30, 60, 120, 40, 90 ]array
Hint

Sort the numbers first, then map: map() keeps the order it is given.

🧑‍🏫 Model answer (for the teacher)

Teacher eyes only: hide the answers before you share your screen.

The answer green = the 5 lines the student writes

// ===== Snack shop shelf =====var snacks = ["Samosa", "Juice", "Pizza", "Idli", "Burger"];var prices = [30, 60, 120, 40, 90]; snacks.sort();console.log("Menu: " + snacks.join(", ")); prices.sort(function (a, b) { return a - b; }); var shown = prices.map(function (p) { return "₹" + p; });console.log("Cheapest first: " + shown.join(", "));

What it prints

Menu: Burger, Idli, Juice, Pizza, Samosa
Cheapest first: ₹30, ₹40, ₹60, ₹90, ₹120

What ✓ Check looks for

  • it prints exactly:
    Menu: Burger, Idli, Juice, Pizza, Samosa
    Cheapest first: ₹30, ₹40, ₹60, ₹90, ₹120
  • In the code: Step 2: sort the prices with return a - b.
  • In the code: Step 3: add ₹ with prices.map().

If they're stuck, say

Sort the numbers first, then map: map() keeps the order it is given.

Class activity 3 of 3

Class register cleanup

Names were typed with random capitals, so sort() puts them in a strange order. Clean them with map(), then sort. When it works it prints:
Before: Riya, aman, Zoe, bilal
After: aman, bilal, riya, zoe

  1. Print the names as they are, after Before:
  2. Use map() to make every name lowercase, in a new array.
  3. Sort the new array and print it after After:
Your code

▶ Output

(nothing is printed)

📦 Memory boxes

names[ 'Riya', 'aman', 'Zoe', 'bilal' ]array
Hint

Ask first: without the cleanup, sort() gives Riya, Zoe, aman, bilal. Why?

🧑‍🏫 Model answer (for the teacher)

Teacher eyes only: hide the answers before you share your screen.

The answer green = the 4 lines the student writes

// ===== Class register cleanup =====var names = ["Riya", "aman", "Zoe", "bilal"]; console.log("Before: " + names.join(", ")); var clean = names.map(function (n) { return n.toLowerCase(); }); clean.sort();console.log("After: " + clean.join(", "));

What it prints

Before: Riya, aman, Zoe, bilal
After: aman, bilal, riya, zoe

What ✓ Check looks for

  • it prints exactly:
    Before: Riya, aman, Zoe, bilal
    After: aman, bilal, riya, zoe
  • In the code: Step 2: use n.toLowerCase() inside map().
  • In the code: Step 2: make the clean names with map().

If they're stuck, say

Ask first: without the cleanup, sort() gives Riya, Zoe, aman, bilal. Why?

After class · project

My movie night list

Plan a movie night: list your favourite films with their running times, then print them A to Z, the shortest film first, the times in hours and minutes with map(), and a top 3 of the longest films.

What to make: A program with two arrays (films and minutes) that prints the films A to Z, the times shortest first, the times in hours and minutes with map(), and the top 3 longest.

Stretch: Keep each film with its time: make an array of strings like "Robo Chef (110)" with map() and the position i, so the names and times stay together when you print them.

How it is marked

Look forDone well when
RunsNo red error when you press Run
A to ZThe films print in alphabetical order
NumbersThe times are sorted by value with a compare function, both ways
map()Every time is shown as hours and minutes, and the original array is kept
Top 3slice(0, 3) prints the three longest films' times

Starter code to take home

Press Copy and paste it into the editor at home, or work on it right here.

Project starter

▶ Output

Movie night!

📦 Memory boxes

films[ 'Space Pals', 'The Lost Kite', 'Robo Chef', 'Ocean Run', 'Night Owl' ]arrayminutes[ 95, 135, 110, 88, 120 ]array
🔑 Show one possible solution (try it yourself first!)
One possible solution

▶ Output

A to Z: Night Owl, Ocean Run, Robo Chef, Space Pals, The Lost Kite
Shortest first: 88, 95, 110, 120, 135
In hours: 1h 28m, 1h 35m, 1h 50m, 2h 0m, 2h 15m
Top 3: 135, 120, 110

📦 Memory boxes

films[ 'Night Owl', 'Ocean Run', 'Robo Chef', 'Space Pals', 'The Lost Kite' ]arrayminutes[ 135, 120, 110, 95, 88 ]arraytimes[ '1h 28m', '1h 35m', '1h 50m', '2h 0m', '2h 15m' ]array

Homework

Practise at home

Each one checks itself. Or print the practice sheet.

Warm-up

1. Sort the planets A to Z and print them joined with ", ".

Homework 1

▶ Output

(nothing is printed)

📦 Memory boxes

planets[ 'Mars', 'Venus', 'Earth', 'Jupiter' ]array
🧑‍🏫 Model answer (for the teacher)

Teacher eyes only: hide the answers before you share your screen.

The answer green = the 2 lines the student writes

var planets = ["Mars", "Venus", "Earth", "Jupiter"];planets.sort();console.log(planets.join(", "));

What it prints

Earth, Jupiter, Mars, Venus

What ✓ Check looks for

  • it prints exactly:
    Earth, Jupiter, Mars, Venus
  • In the code: Use planets.sort().
Core

2. Sort the step counts from most to least and print them, then print only the biggest.

Homework 2

▶ Output

(nothing is printed)

📦 Memory boxes

steps[ 5400, 12000, 800, 9300 ]array
🧑‍🏫 Model answer (for the teacher)

Teacher eyes only: hide the answers before you share your screen.

The answer green = the 3 lines the student writes

var steps = [5400, 12000, 800, 9300];steps.sort(function (a, b) { return b - a; });console.log(steps.join(", "));console.log("Most: " + steps[0]);

What it prints

12000, 9300, 5400, 800
Most: 12000

What ✓ Check looks for

  • it prints exactly:
    12000, 9300, 5400, 800
    Most: 12000
  • In the code: Sort with return b - a.
Core

3. Turn every temperature from Celsius into Fahrenheit with map() (c * 9 / 5 + 32) and print both arrays.

Homework 3

▶ Output

(nothing is printed)

📦 Memory boxes

celsius[ 0, 25, 100 ]array
🧑‍🏫 Model answer (for the teacher)

Teacher eyes only: hide the answers before you share your screen.

The answer green = the 3 lines the student writes

var celsius = [0, 25, 100];var fahrenheit = celsius.map(function (c) { return c * 9 / 5 + 32; });console.log(fahrenheit.join(", "));console.log(celsius.join(", "));

What it prints

32, 77, 212
0, 25, 100

What ✓ Check looks for

  • it prints exactly:
    32, 77, 212
    0, 25, 100
  • In the code: Use celsius.map().
Stretch 🔥

4. Medal table: sort the points highest first, then map them to Gold, Silver, Bronze and then just the points, like Gold: 90

Homework 4

▶ Output

(nothing is printed)

📦 Memory boxes

points[ 72, 90, 65, 81, 58 ]array
🧑‍🏫 Model answer (for the teacher)

Teacher eyes only: hide the answers before you share your screen.

The answer green = the 4 lines the student writes

var points = [72, 90, 65, 81, 58];var medals = ["Gold", "Silver", "Bronze", "4th", "5th"];points.sort(function (a, b) { return b - a; });var table = points.map(function (p, i) { return medals[i] + ": " + p; });console.log(table.join(", "));

What it prints

Gold: 90, Silver: 81, Bronze: 72, 4th: 65, 5th: 58

What ✓ Check looks for

  • it prints exactly:
    Gold: 90, Silver: 81, Bronze: 72, 4th: 65, 5th: 58
  • In the code: Use map() with the position.

🔥 Challenge round · finished early?

The hardest questions of the lesson, no notes

Cover the notes and try these from memory. They are meant to make you think hard: draw, try small cases, and check your answer.

🧠 Think-hard question

Sort the players by their scores, not their names: keep two arrays and use the scores to decide. Hint: sort an array of positions [0, 1, 2, 3, 4] with function (a, b) { return scores[b] - scores[a]; }, then map each position to players[i] + " " + scores[i].

Talk it through or use the drawing board. There is more than one way to get there.

Quiz · 8 questions

Final quiz: check what you learned

Pick an answer to see if it is right and why. Your best score is saved on this device.

1What does this print?
var a = ["pear", "Apple", "banana"];
a.sort();
console.log(a.join(", "));
Show the answer

Apple, banana, pear. Capital A has a smaller letter code than any small letter, so Apple comes first.

2What does this print?
var n = [10, 9, 100];
n.sort();
console.log(n.join(", "));
Show the answer

10, 100, 9. Without a compare function the numbers are compared as text: 10 and 100 start with 1, which comes before 9.

3What does this print?
var a = [3, 1, 2];
a.reverse();
console.log(a.join(", "));
Show the answer

2, 1, 3. reverse() only flips the current order. It does not sort.

4Which line sorts scores from highest to lowest?
Show the answer

scores.sort(function (a, b) { return b - a; });. b - a is positive when b is bigger, which moves the bigger number first.

5What does this print?
var s = [2, 4];
var d = s.map(function (x) { return x * 10; });
console.log(s.join(", "));
Show the answer

2, 4. map() returns a new array and leaves s as it was.

6What does this print?
var s = [6, 9];
var t = s.map(function (x) { x + " pts"; });
console.log("[" + t.join(", ") + "]");
Show the answer

[, ]. The function has no return, so every new item is undefined, and join() shows undefined as an empty piece: only the comma is left.

7A compare function returns a negative number for a and b. What happens?
Show the answer

a goes first. Negative means a comes before b; positive means b comes first; zero keeps their order.

8What does this print?
var s = [30, 10];
var t = s.map(function (x, i) { return (i + 1) + ". " + x; });
console.log(t.join(", "));
Show the answer

1. 30, 2. 10. map() gives the position i starting at 0, so i + 1 is 1 for the first item.

🖨 Print what we learned

Make a worksheet from this lesson

Pick what to practise, then print it or choose Save as PDF in the print window to download it.

Include
Options

For parents and teachers

The 60-minute lesson plan

Use it as it is, or stretch any part over two sessions. Each row links to the part of the page you need.

TimePartThe teacherThe learner
0–4 minWarm-upAsk the scoreboard question and collect two answers: by value and as words.Guess both orders.
4–16 minsort() and reverse()Type along, then predict the example before running it. Do tasks 1.1 to 1.4 together.Type along, predict, practise.
16–28 minSorting numbers with a compare functionShow the trap first. Say the rule out loud: negative means a first.Fix the scoreboard, then practise.
28–40 minmap()Delete return on purpose and run it. Point at the original array after map().Stamp labels, then practise.
40–46 minLeaderboard printoutRead the four steps; let them press Check after each.Follow the steps.
46–51 minSnack shop shelfAsk: should you map first or sort first?Finish the activity.
51–55 minClass register cleanupIf time is short, set it as homework.Try the challenge.
55–59 minQuizRead each question aloud. Vote, then check.Answer and read why.
59–60 minSet the after-class projectOpen the project and agree a due date.Copy the boilerplate.

Questions to ask

  • Why does [10, 9, 100].sort() put 9 last?
  • What does reverse() do to an array that isn't sorted?
  • What does a compare function's answer tell sort()?
  • Why doesn't map() change the original array, and why does it need return?

If it feels hard

Write each item on a sticky note and act the methods out: sort() lines the notes up by their first letter, reverse() flips the row, and map() copies every note onto a new note with a label added, leaving the old row where it was.

If it feels easy

Sort the players by their scores, not their names: keep two arrays and use the scores to decide. Hint: sort an array of positions [0, 1, 2, 3, 4] with function (a, b) { return scores[b] - scores[a]; }, then map each position to players[i] + " " + scores[i].

FAQ

Array sorting and mapping: questions

How do you sort an array in JavaScript?

Call sort() on it, like names.sort(). It changes the original array and puts text in A to Z order, with capital letters before small letters.

Why does sort() put 1200 before 300?

Without a compare function, sort() compares items as text. Use nums.sort(function (a, b) { return a - b; }) to sort numbers by value.

How do you sort numbers from highest to lowest?

Use a compare function that returns b - a: nums.sort(function (a, b) { return b - a; }).

What does map() do?

It runs a function on every item and returns a new array of the results. The original array stays the same; the function needs return.

Start a conversation

Want a teacher to take this class?

Tell us the learner's age and level. A teacher from our network teaches with these lessons; we confirm timing and price first.

  • Tell us the learner’s age or grade and goals
  • We’ll suggest a suitable class or learning path
  • We’ll confirm format, timing and fees with a parent or guardian

For a child’s class, please have a parent or guardian send the enquiry. Avoid sharing passwords or sensitive personal details.

We’ll use your details only to respond to this request.

Chat on WhatsApp
Esc

Try