Skip to content
LumenaryAcademy
Practice 60 min

Arrays, destructuring and collections

The array methods that replace most loops, destructuring and spread, Map and Set, and the iterators behind for...of.

Code tested · 5AI-draftedAwaiting review by a computer scientist
MotivationH

Most programs are about collections

A list of orders, the rows of a spreadsheet, the messages in a chat, the results of a search: most of the data a program handles comes in collections, and most of its code transforms one collection into another. JavaScript's tools for this have grown a lot since 2015, and modern code looks quite different from older code. Where a 2010 program had a for loop with an index, a temporary array and a few ifs, a 2026 program usually has a short chain of filter, map and toSorted, each naming exactly what it does.

This lesson covers the array methods and the main trap among them (sorting), the destructuring and spread syntax that make data easy to unpack and combine, the Map and Set collections and when to prefer them to plain objects, and finally the iteration protocol that ties them all together, with the lazy iterator helpers that arrived in ECMAScript 2025.

Worked examplesH

Arrays, and what changes them

An array is an ordered list, indexed from 0, that grows and shrinks as needed and can hold values of any type (though in good code each array holds one kind of thing). The first thing to learn about its methods is which ones mutate the array and which return a new one.

javascript
// Arrays: ordered, zero-indexed, growable lists of any values.
const queue = ["Ana", "Ben", "Chidi"];
queue.push("Dana");                 // add at the end
const first = queue.shift();        // remove from the start
queue.unshift("Eko");               // add at the start
const last = queue.pop();           // remove from the end
console.log(first, last, queue, queue.length);

console.log(queue[0], queue.at(-1), queue[10]);
console.log(queue.includes("Ben"), queue.indexOf("Chidi"), queue.indexOf("Zoe"));

// Methods that change the array versus methods that return a new one.
const nums = [5, 1, 10, 2];
const sortedCopy = nums.toSorted((a, b) => a - b);    // ES2023: copy
console.log(nums, sortedCopy);
nums.sort();                                           // in place, and as strings!
console.log(nums);
nums.sort((a, b) => a - b);                            // in place, numerically
console.log(nums);

const letters = ["a", "b", "c", "d", "e"];
console.log(letters.slice(1, 3), letters);            // copy of a range
const removed = letters.splice(1, 2, "X");            // remove 2 at index 1, insert "X"
console.log(removed, letters);
console.log(letters.with(0, "A"), letters.toReversed(), letters);

// Building arrays.
console.log(Array.from({ length: 5 }, (_, i) => i * i));
console.log(Array.from("héllo"), [..."abc"].join("-"));
text
Ana Dana [ 'Eko', 'Ben', 'Chidi' ] 3
Eko Chidi undefined
true 2 -1
[ 5, 1, 10, 2 ] [ 1, 2, 5, 10 ]
[ 1, 10, 2, 5 ]
[ 1, 2, 5, 10 ]
[ 'b', 'c' ] [ 'a', 'b', 'c', 'd', 'e' ]
[ 'b', 'c' ] [ 'a', 'X', 'd', 'e' ]
[ 'A', 'X', 'd', 'e' ] [ 'e', 'd', 'X', 'a' ] [ 'a', 'X', 'd', 'e' ]
[ 0, 1, 4, 9, 16 ]
[ 'h', 'é', 'l', 'l', 'o' ] a-b-c
Mutates the arrayReturns a new array or value instead
push, pop, shift, unshiftconcat, spread [...a, x]
sort, reversetoSorted, toReversed (ES2023)
splicetoSpliced (ES2023), slice
arr[i] = x, fill, copyWithinwith(i, x) (ES2023)

The single most important line in the program is the default sort(), which turned [5, 1, 10, 2] into [1, 10, 2, 5]. With no comparator, sort converts elements to strings and compares them as text, and "10" comes before "2" just as "ba" comes before "c". Always pass a comparator when sorting anything but strings: (a, b) => a - b for ascending numbers, (a, b) => a.localeCompare(b) for words people will read. Since 2019 the standard requires sorting to be stable: elements that compare equal keep their original order, so you can sort by one key and then by another.

Reading past the end, queue[10], gives undefined rather than an error. at(-1) reads from the end. indexOf returns -1 when the value is absent, which is why includes is clearer for yes-or-no questions. Array.from builds an array from anything iterable or array-like, and its second argument maps each element: Array.from({ length: 5 }, (_, i) => i * i) is the idiom for "an array of n computed values" (the _ names a parameter you don't use).

Many teams prefer the non-mutating methods by default, because data that is never changed in place cannot be changed by surprise by some other part of the program that holds a reference to it. That is also how UI frameworks such as React detect changes: they compare references, so you must create a new array rather than modify the old one.

ComputationC

map, filter, reduce and friends

These methods take a callback and replace most hand-written loops. Each callback receives the element, its index and the whole array, though you usually need only the element.

javascript
// The array methods professionals use every day, on a small data set.
const loans = [
  { title: "Things Fall Apart", author: "Achebe", days: 12, branch: "Central" },
  { title: "One Hundred Years of Solitude", author: "García Márquez", days: 30, branch: "East" },
  { title: "The Tale of Genji", author: "Murasaki", days: 21, branch: "Central" },
  { title: "Season of Migration to the North", author: "Salih", days: 5, branch: "East" },
  { title: "Pedro Páramo", author: "Rulfo", days: 18, branch: "West" },
];

// map: transform each element.
console.log(loans.map((loan) => loan.author));

// filter: keep the elements that pass a test.
const overdue = loans.filter((loan) => loan.days > 14);
console.log(overdue.length, "overdue");

// find / findIndex / some / every: search.
console.log(loans.find((loan) => loan.branch === "West")?.title);
console.log(loans.findIndex((loan) => loan.days < 10));
console.log(loans.some((loan) => loan.days > 28), loans.every((loan) => loan.days > 1));

// reduce: fold the array into one value.
const totalDays = loans.reduce((sum, loan) => sum + loan.days, 0);
console.log("total days on loan:", totalDays);

// A pipeline: overdue loans, longest first, as a report.
const fineCentsPerDay = 25;
const report = loans
  .filter((loan) => loan.days > 14)
  .toSorted((a, b) => b.days - a.days)
  .map((loan) => {
    const fine = ((loan.days - 14) * fineCentsPerDay / 100).toFixed(2);
    return `${loan.title.padEnd(30)} ${String(loan.days).padStart(3)} days  fine ${fine}`;
  });
console.log(report.join("\n"));

// flatMap: map, then flatten one level.
const words = ["red sun", "blue sea"].flatMap((phrase) => phrase.split(" "));
console.log(words);
text
[ 'Achebe', 'García Márquez', 'Murasaki', 'Salih', 'Rulfo' ]
3 overdue
Pedro Páramo
3
true true
total days on loan: 86
One Hundred Years of Solitude   30 days  fine 4.00
The Tale of Genji               21 days  fine 1.75
Pedro Páramo                    18 days  fine 1.00
[ 'red', 'sun', 'blue', 'sea' ]
MethodReturnsUse it to
map(f)a new array of the same lengthtransform each element
filter(test)a new array of the elements that passselect
find(test), findLast(test)the first (or last) matching element, or undefinedlook something up
findIndex(test)its index, or -1locate something to replace
some(test), every(test)a boolean; they stop earlyask "any?" or "all?"
reduce(f, initial)one value built up step by stepsum, count, build an object
flatMap(f)map then flatten one leveleach element becomes zero or more results
forEach(f)undefinedrun a side effect for each element

Some practical advice. Always give reduce an initial value: without one, it uses the first element, and an empty array throws a TypeError. Prefer the specific method to reduce when one exists: filter(...).length or a plain loop is often clearer than a clever reduce. forEach cannot be stopped with break; when you might stop early, use for...of, some or find. And chains like the report above are not only readable, they are also correct by construction: each step does one job and cannot interfere with the others.

A note on cost: each step of a chain creates a new array. For the hundreds or thousands of elements typical in application code that is negligible. For millions, a single loop, or the lazy iterator helpers at the end of this lesson, avoids the intermediate arrays.

Worked examplesH

Destructuring and spread

Definition— destructuring and spread

Destructuring is a pattern on the left of = (or in a parameter list) that unpacks an array by position or an object by property name into separate variables. Spread, ... in an array literal, a function call or an object literal, expands an iterable's elements or an object's own properties in place. The same ... in a pattern is a rest element, which gathers what is left.

javascript
// Destructuring: unpack arrays and objects into variables.
const [gold, silver, ...others] = ["Kenya", "Ethiopia", "Uganda", "Eritrea"];
console.log(gold, silver, others);

const [, second = "none", third = "none"] = ["only", "two"];
console.log(second, third);                     // a skipped element, and a default

let a = 1;
let b = 2;
[a, b] = [b, a];                                 // swap without a temporary
console.log(a, b);

const user = { id: 7, name: "Nadia", address: { city: "Tunis", zip: "1000" } };
const { name, role = "member", address: { city } } = user;
console.log(name, role, city);

const { id: userId, ...publicFields } = user;   // rename, and collect the rest
console.log(userId, publicFields);

// Destructuring parameters: named, optional arguments with defaults.
function formatPrice(amount, { currency = "EUR", locale = "en", digits = 2 } = {}) {
  return new Intl.NumberFormat(locale, {
    style: "currency",
    currency,
    minimumFractionDigits: digits,
  }).format(amount);
}
console.log(formatPrice(1234567.5));
console.log(formatPrice(1234567.5, { currency: "INR", locale: "en-IN" }));
console.log(formatPrice(1234567.5, { currency: "JPY", locale: "ja-JP", digits: 0 }));

// Spread: expand an iterable or an object in place.
const weekdays = ["Mon", "Tue", "Wed", "Thu", "Fri"];
const week = [...weekdays, "Sat", "Sun"];
console.log(week.length, Math.max(...[3, 9, 4]));

const defaults = { theme: "light", fontSize: 14, showTips: true };
const saved = { fontSize: 18 };
console.log({ ...defaults, ...saved });          // later properties win
text
Kenya Ethiopia [ 'Uganda', 'Eritrea' ]
two none
2 1
Nadia member Tunis
7 { name: 'Nadia', address: { city: 'Tunis', zip: '1000' } }
€1,234,567.50
₹12,34,567.50
¥1,234,568
7 9
{ theme: 'light', fontSize: 18, showTips: true }

Patterns mirror the literals they unpack: square brackets match by position, braces by name. Defaults (role = "member") apply only when the value is undefined, exactly as for parameters. address: { city } reaches into a nested object; id: userId renames; ...publicFields collects every property not already taken, a neat way to drop a field from a copy.

formatPrice shows the options object pattern promised in lesson three: callers name only the options they care about, in any order, and the trailing = {} lets them leave the options out entirely. It also shows why you should format money and numbers with Intl.NumberFormat rather than by hand: Indian English groups digits in lakhs and crores (12,34,567.50), and the yen has no minor unit.

Spread and rest appear everywhere: [...a, ...b] to concatenate, { ...defaults, ...saved } to merge settings (later properties win), Math.max(...nums) to pass an array as separate arguments, and [a, b] = [b, a] to swap.

IntuitionH

Map and Set

Plain objects make poor general-purpose dictionaries: keys are always strings, inherited names like toString can collide with yours, and there is no direct way to ask for the size. ECMAScript 2015 added two proper collections.

javascript
// Map: a dictionary with keys of any type, kept in insertion order.
const stock = new Map([
  ["rice", 40],
  ["lentils", 12],
]);
stock.set("millet", 25);
stock.set("rice", stock.get("rice") - 5);
console.log(stock.size, stock.get("rice"), stock.has("teff"), stock.get("teff"));
for (const [item, qty] of stock) {
  console.log(`${item}: ${qty}`);
}

// Keys can be objects: here, each visitor object maps to a visit count.
const ama = { name: "Ama" };
const visits = new Map([[ama, 3]]);
console.log(visits.get(ama), visits.get({ name: "Ama" }));

// Set: unique values. ES2025 adds union, intersection, difference and more.
const tags = new Set(["js", "web", "js", "node"]);
console.log(tags.size, [...tags]);
const python = new Set(["python", "data", "web"]);
const js = new Set(["js", "web", "node"]);
console.log(js.union(python));
console.log(js.intersection(python), js.difference(python));
console.log(new Set(["web"]).isSubsetOf(js), js.isDisjointFrom(new Set(["rust"])));

// Remove duplicates from an array in one line.
console.log([...new Set([3, 1, 3, 2, 1])]);

// Grouping (ES2024): Object.groupBy gives a plain object, Map.groupBy a Map.
const readings = [
  { city: "Lima", temp: 19 },
  { city: "Oslo", temp: -3 },
  { city: "Lima", temp: 21 },
  { city: "Oslo", temp: 1 },
];
const byCity = Object.groupBy(readings, (r) => r.city);
console.log(Object.keys(byCity), byCity.Oslo.map((r) => r.temp));
const bySign = Map.groupBy(readings, (r) => (r.temp < 0 ? "below zero" : "above zero"));
console.log(bySign.get("below zero").length, bySign.get("above zero").length);
text
3 35 false undefined
rice: 35
lentils: 12
millet: 25
3 undefined
3 [ 'js', 'web', 'node' ]
Set(5) { 'js', 'web', 'node', 'python', 'data' }
Set(1) { 'web' } Set(2) { 'js', 'node' }
true true
[ 3, 1, 2 ]
[ 'Lima', 'Oslo' ] [ -3, 1 ]
1 3

A Map accepts keys of any type, compares them like === (except that NaN equals itself), remembers insertion order, and has size, get, set, has, delete and clear. Because object keys are compared by identity, visits.get({ name: "Ama" }) is undefined: that is a different object. A Set stores each value once, by the same rule.

The Set methods union, intersection, difference, symmetricDifference, isSubsetOf, isSupersetOf and isDisjointFrom are new in ECMAScript 2025, and they are the familiar operations of Lumenary Math's sets. Before them, every project wrote its own with filter and has. Object.groupBy and Map.groupBy (ECMAScript 2024) replace another hand-written reduce that every project used to contain.

Which to use:

You needUse
an ordered list, possibly with repeatsan array
a record with fixed, known field names (a user, an order)a plain object
a dictionary whose keys come from data, or are not stringsa Map
fast "have I seen this?" tests, or unique valuesa Set
extra data attached to objects you don't own, without keeping them alivea WeakMap

Map and Set lookups take constant time on average, like the hash tables they are built on, so replacing array.includes(x) inside a loop with a Set can turn a quadratic algorithm into a linear one. One limitation: JSON.stringify does not understand them (a Map becomes {}), so convert with Object.fromEntries(map) or [...set] before sending them anywhere.

Typed arrays, for bytes and numbers in bulk

Ordinary arrays can hold anything, which makes them flexible but not compact. When a program handles raw bytes (a file, an image, a network message, data shared with WebAssembly) or millions of numbers of one kind, JavaScript offers typed arrays: Uint8Array, Int32Array, Float64Array and their siblings. Each is a fixed-length view onto a block of memory, an ArrayBuffer, holding numbers of exactly one machine type. new Uint8Array(4) is four zero bytes; storing 300 in one of them keeps only the low eight bits, 44, because a byte cannot hold more. Typed arrays share most array methods (map, slice, sort, which for them sorts numerically by default), and they are what fetch responses, the TextEncoder and Node's file APIs hand you when you ask for bytes. You will meet them as soon as you work with binary data; for everyday lists, stay with ordinary arrays.

ComputationC

Iterators, generators and the ES2025 helpers

What do arrays, strings, maps and sets have in common that lets for...of, spread and destructuring work on all of them? They are iterable: they have a method stored under the well-known symbol Symbol.iterator that returns an iterator, an object whose next() method hands out values one at a time. You can make your own, and the easiest way is a generator, a function written function* that can pause at each yield.

javascript
// Iterables: anything for...of and spread can walk, defined by Symbol.iterator.
class Countdown {
  constructor(from) {
    this.from = from;
  }
  *[Symbol.iterator]() {          // a generator method: yields values one at a time
    for (let n = this.from; n > 0; n--) yield n;
  }
}
console.log([...new Countdown(5)]);

// A generator can be infinite: values are produced only when asked for.
function* naturals() {
  let n = 1;
  while (true) yield n++;
}

// Iterator helpers (ES2025): lazy map, filter, take, drop, toArray, and more.
const firstSquaresOfOdds = naturals()
  .filter((n) => n % 2 === 1)
  .map((n) => n * n)
  .take(5)
  .toArray();
console.log(firstSquaresOfOdds);

// Laziness: only as many values are computed as are needed.
let produced = 0;
function* counted() {
  for (const n of naturals()) {
    produced++;
    yield n;
  }
}
const firstOver100 = counted().map((n) => n * 7).find((n) => n > 100);
console.log(firstOver100, "after producing", produced, "values");

// Maps, sets and arrays all have iterator methods too.
const prices = new Map([["tea", 3], ["cake", 5], ["soup", 7]]);
console.log(prices.keys().filter((k) => k.length === 4).toArray());
console.log(prices.values().reduce((sum, p) => sum + p, 0));
text
[ 5, 4, 3, 2, 1 ]
[ 1, 9, 25, 49, 81 ]
105 after producing 15 values
[ 'cake', 'soup' ]
15

naturals() never ends, and that is fine, because a generator runs only when asked for its next value. Iterator helpers, added in ECMAScript 2025, give every iterator map, filter, take, drop, flatMap, reduce, toArray, forEach, some, every and find. Unlike the array methods, they are lazy: each value flows through the whole chain before the next is produced, and nothing is computed that is not needed. The counter shows it: finding the first multiple of 7 above 100 produced exactly 15 values, and there were no intermediate arrays.

Use array methods for data that is already in an array, and iterator helpers for sequences that are large, infinite, or expensive to produce: lines of a big file, pages of results from an API, map.keys() (as the last lines show, no [...spread] needed first). They are available in Node 22 and in current versions of all major browsers.

Common misconceptionsH

Common misconceptions

Misconception

"sort() sorts numbers." With no comparator it sorts by string comparison, so [10, 9, 1, 100].sort() gives [1, 10, 100, 9]. Pass (a, b) => a - b.

Misconception

"map is just a shorter forEach." map builds and returns a new array of results; forEach returns undefined and exists for side effects. Using map only for its side effects creates an array that nobody reads, and linters flag it.

Misconception

"Spread makes a copy, so changing the copy is safe." Spread copies one level. Objects nested inside are shared between the original and the copy, as lesson five showed. Use structuredClone for an independent deep copy.

Misconception

"A Map is just a fancier object." It differs in ways that matter: keys of any type, no inherited keys, a reliable size, insertion order for every key, and better performance when keys are added and removed often. Objects remain the right choice for records with fixed fields and for JSON.

Exercises

Exercises

Say for each one whether anything is mutated, then predict the output.

1. Arrays, destructuring and collections

Warm-upComputational

What does console.log([10, 9, 1, 100].sort()) print? Write it as Node shows an array, for example [ 1, 2, 3 ].

2. Arrays, destructuring and collections

Warm-upComputational

What number does this print?

console.log([1, 2, 3, 4].reduce((acc, x) => acc * x, 1) + [].reduce((a, b) => a + b, 10));

3. Arrays, destructuring and collections

CoreComputational

What does this print?

const { a = 1, b = 2 } = { a: undefined, b: null };
console.log(a, b);

4. Arrays, destructuring and collections

CoreComputational

What does this print? Write it as Node shows an object, for example { x: 1 }.

console.log({ ...{ x: 1, y: 2 }, x: 3, ...{ y: 4 } });

5. Arrays, destructuring and collections

CoreComputational

What does console.log(new Set("mississippi").size) print?

6. Arrays, destructuring and collections

StretchComputational

What does this print?

const m = new Map();
m.set("1", "a");
m.set(1, "b");
const o = {};
o["1"] = "a";
o[1] = "b";
console.log(m.size, Object.keys(o).length);

7. Arrays, destructuring and collections

StretchComputational

What does this print? Write it as Node shows an array, for example [ 1, 2, 3 ].

function* naturals() {
  let n = 1;
  while (true) yield n++;
}
console.log(naturals().map((n) => n * 3).filter((n) => n % 2 === 0).take(3).toArray());

8. Arrays, destructuring and collections

CoreHuman

Which of these calls change the array arr itself? Choose all that apply.

Choose all that apply

Further reading and resources