JavaScript · Lesson 7

Arrays

Creating arrays, the methods that change an array versus the ones that return a new one, map, filter and reduce, sorting with comparators, grouping, and the performance traps that turn a fast loop into a slow one.

13 min read

In short

  • sort, reverse, splice and push change the array
  • toSorted, toReversed, toSpliced, with return copies
  • Give reduce a starting value
  • Always pass a comparator: subtract numbers, localeCompare strings
  • Object.groupBy and Map.groupBy for grouping
  • No includes or find inside a loop: index with a Set or Map

Arrays are the data structure you use most in JavaScript. API responses are arrays, React renders lists from arrays, and most "business logic" in a frontend is some mix of filtering, sorting, grouping and summing them. The language gives you a large toolbox of array methods, and nearly all the bugs come from two questions:

  1. Does this method change the array, or return a new one? Get this wrong and you change state that React or Angular thinks hasn't changed, or you sort an array someone else is still using.
  2. How is this compared? The default sort compares strings, includes and indexOf disagree about NaN, and a comparator that returns a boolean quietly does nothing.

This lesson builds the right picture for both, then covers grouping and the performance traps that show up in code review. Every snippet has a ▶ Try button. Predict the output, then run it.

The mental model: an object with numbered keys

A JavaScript array is an object whose keys are "0", "1", "2" and so on, plus a length property that is always one more than the highest index. It can hold any mix of values, it grows and shrinks as you like, and there's no fixed size or element type as there is in C#.

▶ Try
const items = ['a', 'b', 'c'];
console.log(typeof items, Array.isArray(items)); // object true
console.log(items.length, items[1], items[10]);  // 3 b undefined (no error out of bounds)
console.log(items.at(-1));                      // c: at() accepts negative indexes

items.length = 1; // shrinking length deletes the extra items
console.log(items);

Two consequences:

  • Reading past the end gives undefined, not an exception. A typo in an index is a silent bug.
  • typeof says 'object'. Use Array.isArray(value) to check for an array.

Creating arrays

▶ Try
console.log(Array.from('héllo'));                        // from any iterable
console.log(Array.from(new Set([3, 3, 1])));             // a quick way to dedupe
console.log(Array.from({ length: 4 }, (_, i) => i * i)); // a range with a map function
console.log(Array.of(3));                                // [3], one item
console.log(new Array(3).fill(0));                       // [0, 0, 0]

Array.from({ length: n }, fn) is the idiom for "an array of n things". Its second argument is a map function that gets (value, index), and value is always undefined here, so name it _.

Holes: why new Array(3) is a trap

new Array(3) (or Array(3)) doesn't create three undefined values. It creates an array with length 3 and no items at all. Those missing slots are called holes, and most methods skip them:

▶ Try
const holes = new Array(3);
console.log(holes.length, Object.keys(holes).length); // 3 0
console.log(holes.map(() => 'x').join('-'));          // "--": map skipped every slot
console.log(Array.from({ length: 3 }, () => 'x'));    // real values, so this works

forEach, map, filter, some and reduce skip holes. for...of, spread, Array.from and the newer methods (toSorted, with, at) treat them as undefined. You rarely want holes, so create arrays with Array.from or fill.

fill has its own trap: it puts the same value in every slot. With an object or array, every slot points to one shared object.

▶ Try
const grid = new Array(3).fill([]);
grid[0].push('x');
console.log(grid); // every row changed: it's one array, three times

const safe = Array.from({ length: 3 }, () => []);
safe[0].push('x');
console.log(safe); // only the first row

Mutating and non-mutating methods

This is the most important table in the lesson.

Changes the array (mutates)Returns a new array instead
push, pop, shift, unshift[...items, x], items.slice(0, -1), items.slice(1), [x, ...items]
splice(start, deleteCount, ...add)toSpliced(start, deleteCount, ...add)
sort(compare)toSorted(compare)
reverse()toReversed()
items[i] = valuewith(i, value)
fill, copyWithinmap, filter, slice, concat, flat, flatMap

toSorted, toReversed, toSpliced and with arrived in ES2023 (Node 20, every current browser). Before them, people wrote [...items].sort(...), which you'll still see everywhere.

▶ Try
const scores = [30, 10, 20];

const sorted = scores.toSorted((a, b) => a - b);
console.log(scores, sorted);       // original untouched

const same = scores.sort((a, b) => a - b);
console.log(scores, same === scores); // sort changed scores AND returned the same array

console.log(scores.with(0, 99), scores); // a copy with one item replaced
console.log(scores.toSpliced(1, 1), scores); // a copy with one item removed

The trap in the middle example: sort and reverse return the array, so const sorted = items.sort() looks like it makes a copy. It doesn't. sorted and items are the same array, and anything else holding items (a React prop, a cached API response) now sees it sorted.

Why frameworks care

React decides whether to re-render by comparing references: Object.is(oldState, newState). Angular's OnPush change detection and signals do the same. If you push into an array that's in state, the reference doesn't change, so nothing updates. The rule for state is simple: never mutate it, always return a new array, and keep the items you didn't change as they are (same references), so memoized children can skip work. The Immutable todo updates exercise practises exactly this.

All of these copies are shallow. [...items] is a new array holding the same objects. Changing copy[0].done changes items[0].done too. To change one item, replace it with a new object: items.map((t) => (t.id === id ? { ...t, done: true } : t)).

map, filter, reduce and friends

▶ Try
const orders = [
  { id: 1, customer: 'ann', total: 120, paid: true },
  { id: 2, customer: 'bob', total: 80, paid: false },
  { id: 3, customer: 'ann', total: 45, paid: true },
];

console.log(orders.map((o) => o.id));                     // transform each item
console.log(orders.filter((o) => o.paid).length);          // keep some
console.log(orders.reduce((sum, o) => sum + o.total, 0));  // fold into one value
console.log(orders.find((o) => o.customer === 'ann').id);  // first match (or undefined)
console.log(orders.findLast((o) => o.customer === 'ann').id); // last match
console.log(orders.some((o) => !o.paid), orders.every((o) => o.total > 50));

The details people get wrong:

  • reduce needs an initial value. Without one, it uses the first item as the start and skips it, and on an empty array it throws TypeError: Reduce of empty array with no initial value. Always pass the second argument.
  • find returns undefined when nothing matches, and findIndex returns -1. Check before using the result.
  • every on an empty array is true and some is false. "All zero orders are paid" is vacuously true, which can surprise you in a validation check.
  • forEach can't stop early and doesn't wait for async callbacks. Use for...of when you need break or await.
  • map passes three arguments (item, index, array). That's why ['1', '2', '3'].map(parseInt) gives [1, NaN, NaN]: parseInt reads the index as its radix. Write .map((s) => parseInt(s, 10)) or .map(Number).

flat and flatMap deal with nested arrays. flatMap is map followed by flat(1), and it doubles as "map and filter in one pass": return [] to drop an item, or several items to expand it.

▶ Try
console.log([1, [2, [3, [4]]]].flat());          // one level by default
console.log([1, [2, [3, [4]]]].flat(Infinity));  // all the way down
console.log(['a b', 'c'].flatMap((s) => s.split(' ')));
console.log([1, 2, 3, 4].flatMap((n) => (n % 2 ? [] : [n * 10])));

includes, indexOf and NaN

Two ways to ask "is this in the array?" that disagree on one value:

▶ Try
const values = [1, NaN, 3];
console.log(values.includes(NaN)); // true
console.log(values.indexOf(NaN));  // -1
console.log([1, 2, 3].includes('2')); // false: no type coercion

indexOf uses ===, and NaN === NaN is false. includes uses SameValueZero: like ===, except NaN equals NaN. Set and Map use SameValueZero too, so a Set can hold one NaN. Use includes for "is it there?" and indexOf only when you need the position. Both compare objects by reference, so [{ id: 1 }].includes({ id: 1 }) is false. For objects, use some((x) => x.id === id).

Sorting

The default sort compares strings

▶ Try
console.log([10, 9, 1, 2].sort()); // [1, 10, 2, 9]
console.log(['b', 'a', 'C'].sort()); // C first: uppercase letters come before lowercase

Without a comparator, sort converts every item to a string and compares UTF-16 code units. That's why 10 sorts before 2 ("1" comes before "2") and "C" before "a". There's almost never a good reason to call sort() without a comparator.

Writing comparators

A comparator (a, b) => number returns a negative number if a goes first, a positive number if b goes first, and 0 if they're equal.

▶ Try
const people = [
  { name: 'Émile', age: 31 },
  { name: 'bob', age: 25 },
  { name: 'Ann', age: 31 },
];

// numbers: subtract (b - a for descending)
console.log(people.toSorted((a, b) => a.age - b.age).map((p) => p.name));

// strings: localeCompare handles case and accents like a human would
console.log(people.toSorted((a, b) => a.name.localeCompare(b.name)).map((p) => p.name));

// "item10" after "item9": a collator with numeric sorting
const byNumber = new Intl.Collator(undefined, { numeric: true }).compare;
console.log(['item10', 'item9', 'item1'].toSorted(byNumber));

Things that break comparators:

  • Returning a boolean. (a, b) => a > b returns true or false, which become 1 or 0. It never says "a goes first", so the result depends on the engine's algorithm. In V8, [5, 1, 4].sort((a, b) => a > b) leaves the array as it was.
  • Subtracting strings. 'b' - 'a' is NaN, which the sort treats like 0.
  • Missing values. undefined is always moved to the end without calling your comparator, but null is passed in, and null - 5 is -5. Decide where empty values go and handle them first.
  • Dates: subtract them (a.date - b.date converts both to milliseconds) or compare getTime().

Multi-key sorts and stability

To sort by several keys, compare the first key and only fall through to the next one when it's a tie. Since every non-zero number is truthy, || does this neatly:

▶ Try
const staff = [
  { team: 'web', name: 'Cy', joined: 2021 },
  { team: 'api', name: 'Bo', joined: 2019 },
  { team: 'web', name: 'Al', joined: 2019 },
  { team: 'api', name: 'Di', joined: 2019 },
];

const sorted = staff.toSorted(
  (a, b) => a.team.localeCompare(b.team) || a.joined - b.joined || a.name.localeCompare(b.name),
);
console.log(sorted.map((s) => `${s.team} ${s.joined} ${s.name}`));

Since ES2019, sort is stable: items that compare equal keep their original order. That gives you a second technique. To get "by team, then by name", you can sort by name first and then by team, and the name order survives inside each team. Stability is also why "sort by the clicked column" in a table keeps the previous order for ties, which users expect.

Grouping: Object.groupBy and Map.groupBy

Grouping used to be a reduce. ES2024 added two built-ins (Node 21+, every current browser):

▶ Try
const orders = [
  { id: 1, customer: 'ann', status: 'paid', total: 120 },
  { id: 2, customer: 'bob', status: 'open', total: 80 },
  { id: 3, customer: 'ann', status: 'open', total: 45 },
];

const byStatus = Object.groupBy(orders, (o) => o.status);
console.log(Object.keys(byStatus), byStatus.open.map((o) => o.id));

const byCustomer = Map.groupBy(orders, (o) => o.customer);
for (const [customer, list] of byCustomer) {
  console.log(customer, list.reduce((sum, o) => sum + o.total, 0));
}
  • Object.groupBy returns a plain object whose keys are strings (the callback's result is converted). The object has a null prototype, so it has no toString or hasOwnProperty methods, and a group named "constructor" is safe. Use Object.keys or Object.entries to walk it.
  • Map.groupBy returns a Map, so keys can be numbers, objects or dates without being turned into strings, and the groups keep the order in which each key was first seen.
  • Both are static methods (Object.groupBy(items, fn)), not items.groupBy(fn). A method on Array.prototype would have broken old websites that added their own groupBy.

On older runtimes, the same thing as a reduce:

▶ Try
const groupBy = (items, keyOf) =>
  items.reduce((groups, item) => {
    (groups[keyOf(item)] ??= []).push(item);
    return groups;
  }, {});

console.log(groupBy(['apple', 'avocado', 'banana'], (s) => s[0]));

Performance traps

Array methods are fast. What hurts is a hidden loop inside a loop. These all look like one line and cost O(n × m):

  • includes, indexOf, find, findIndex or some inside map, filter or a for loop.
  • items.filter((x, i) => items.indexOf(x) === i) to dedupe.
  • reduce that copies its accumulator every step: (acc, x) => ({ ...acc, [x.id]: x }) or (acc, x) => [...acc, x]. Each spread copies everything so far.
▶ Try
const ids = Array.from({ length: 20_000 }, (_, i) => i);
const wanted = ids.filter((id) => id % 2 === 0);

let t = Date.now();
ids.filter((id) => wanted.includes(id)); // 20,000 x 10,000 comparisons
const slow = Date.now() - t;

t = Date.now();
const wantedSet = new Set(wanted); // build the index once
ids.filter((id) => wantedSet.has(id)); // each lookup is O(1)
const fast = Date.now() - t;

console.log(slow > fast * 10 ? 'the Set version is much faster' : 'try a bigger array');

The fix is always the same: build an index once (new Set(ids) or new Map(items.map((x) => [x.id, x]))), then look things up in it. With 100 items none of this matters. With 10,000 rows from an API, the quadratic version freezes the page for seconds. The Dedupe by key and Diff two lists exercises have tests that time out on the quadratic version.

Chaining filter().map().slice() makes several passes and several arrays. That's fine for UI-sized data, and it's much easier to read than a hand-written loop. Reach for one for...of loop only when profiling says so.

Coming from C# or TypeScript

Side note
  • LINQ to array methods: Select is map, Where is filter, Aggregate is reduce, FirstOrDefault is find, Any is some, All is every, SelectMany is flatMap, GroupBy is Object.groupBy or Map.groupBy, Distinct is [...new Set(items)], and OrderBy(...).ThenBy(...) is toSorted with a comparator that chains with ||.
  • Eager, not lazy. LINQ queries run when you enumerate them. Array methods run right away and build a new array at every step. For lazy pipelines, Node 22 and current browsers have iterator helpers (items.values().filter(...).map(...).toArray()), which most codebases don't use yet.
  • List<T>.Sort() mutates, like sort. There's no OrderBy-style copy by default; that's what toSorted is.
  • TypeScript's readonly T[] removes push, sort and friends from the type, so the compiler catches mutation of state. It's types only: at runtime it's a normal array. Object.freeze(items) enforces it at runtime: push on a frozen array throws, in strict and sloppy mode alike.

In real codebases

Side note
  • State updates are array methods: add with [...items, item], remove with filter, update with map and a spread, reorder with toSpliced. Redux Toolkit and Angular's signal update expect the same new-array style (Redux Toolkit lets you write push inside its reducers because Immer turns it into a copy).
  • Derived data (sorted, filtered, grouped views of a list) is computed from state, not stored. In React that's a useMemo, in Angular a computed signal. A sort instead of a toSorted in there mutates the state it was derived from.
  • Lookups by id: turn the array into a Map once, when the data arrives, instead of calling find in every row's render.
  • Money is usually stored in integer cents, so reduce sums are exact. 0.1 + 0.2 is not 0.3.
  • lodash (groupBy, sortBy, uniqBy, chunk, zip) is in a lot of older code. Most of it now has a short native equivalent, and several exercises build one.

The exercises

  1. Chunk and zip (easy): two small utilities, Array.from and slice.
  2. Dedupe by key (easy): keep the first of each key, with a Set, fast on big inputs.
  3. Running totals (easy): a running balance with reduce or map.
  4. Immutable todo updates (medium): add, toggle, rename, remove and move, without mutating.
  5. Paginate (medium): page maths, clamping and slice.
  6. Summarise orders (medium): Object.groupBy, Map.groupBy and reduce.
  7. Multi-key stable sort (hard): a sortBy with directions, strings, dates and empty values.
  8. Diff two lists (hard): added, removed and changed items, with a Map index.

Practise this lesson

In the app: a short video, 8 exercises checked by real tests and a 12-question concept check. Free with a GitHub account.

Open in the app