Skip to content
Lesson 10 of 15

Step 1 of 5 · Reading · ~3 min

Learn

Collections

Arrays and Tuples

An array holds many values of one type; a tuple holds a fixed set of values whose types may differ by position. By the end of this lesson you can add, remove and copy array elements safely, sort with a comparator instead of trusting the default order, and use tuples and destructuring to pass small records around.

Typed arrays

const temps: number[] = [21, 19, 25];
temps.push(30);          // OK, now four elements
temps.push("warm");      // compile error: "warm" is not a number

number[] and Array<number> mean the same thing; T[] is the everyday spelling. Everything you derive stays typed:

const rounded: number[] = temps.map(t => Math.round(t));
const first: number = temps[0];

The everyday operations:

temps.length;            // 4
temps.push(18);          // add to the end, returns the new length
temps.pop();             // remove and return the last element
temps.shift();           // remove and return the first element
temps.indexOf(25);       // position of the first 25, or -1
temps.includes(19);      // true
temps.slice(1, 3);       // new array of positions 1 and 2 (end is excluded)
temps.slice(0, 100);     // fine: an end past the array is clamped
const copy = [...temps]; // spread makes a shallow copy

slice never changes the original. push, pop, shift and sort do change it in place.

Sorting: the default order is text

const sizes: number[] = [10, 9, 1];
sizes.sort();                    // [1, 10, 9]: compared as TEXT, "10" < "9"
sizes.sort((a, b) => a - b);     // [1, 9, 10]: numeric, ascending
sizes.sort((a, b) => b - a);     // [10, 9, 1]: numeric, descending

Without a function, sort converts elements to strings and compares them, so ten sorts before nine. A comparator takes two elements and returns a negative number if the first should come earlier, a positive number if later, and 0 for a tie. Subtraction does that for numbers. The comparator must return a number, not a boolean: (a, b) => a > b returns only true or false, which never signals "earlier", and the order comes out wrong.

sort also reorders the original array and returns that same array. Sort a copy when you need the original: [...sizes].sort(...).

For text, compare with < and >, because there is no subtraction:

const words: string[] = ["pear", "fig", "apple", "kiwi"];
words.sort((a, b) => a.length - b.length || (a < b ? -1 : a > b ? 1 : 0));
// ["fig", "kiwi", "pear", "apple"]: shortest first, ties alphabetical

|| works as a tiebreaker here because a.length - b.length is 0 exactly when the lengths tie, and 0 is falsy, so the second comparison is used.

Tuples: fixed positions, fixed types

An array says "many values, one type". A tuple says "exactly these positions, each with its own type":

type Reading = [string, number];            // [sensor name, value]
const r: Reading = ["kitchen", 21.5];
const readings: Reading[] = [["kitchen", 21.5], ["garage", 14]];

const [sensor, value] = r;                  // destructuring: sensor is string, value is number
console.log(readings[1][0]);                // "garage"

Destructuring unpacks positions into named variables with the right types. It works in loop heads as well: for (const [sensor, value] of readings). Tuples appear constantly in real APIs: Object.entries(obj) yields [string, V] pairs, and a Map iterates as [key, value] pairs.

Common mistakes

  • Calling sort() on numbers with no comparator. [10, 9, 1] becomes [1, 10, 9].
  • A comparator that returns a boolean. It must return a negative, zero or positive number.
  • Ignoring ties. When two elements compare equal their order is arbitrary unless you add a second key.
  • Sorting the only copy. sort mutates; copy first if the original order still matters.
  • Mixing up slice(start, end). The end index is excluded, so slice(0, 3) keeps three elements.

Your exercise

Rank players by score. Each input line becomes a [name, score] tuple, and you must order the tuples correctly, including ties, and print only the top few. The starter reads the input into tuples. The hidden tests catch the default text sort, an ascending order, and unhandled ties.

Up nextRecords and MapsCollections

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…