JavaScript arrays: map, filter, reduce, find and sort without surprises
The array methods you use every day, which ones change the array and which return a new one, and the sort() bug that bites everyone who sorts numbers.
Most JavaScript code moves data through arrays: read something, transform it, keep some of it, summarise it. A small set of methods covers nearly all of it.
Transform, keep, summarise
const tickets = [
{ film: "Dune", seats: 2, price: 11 },
{ film: "Heat", seats: 4, price: 9 },
{ film: "Dune", seats: 1, price: 11 },
];
const totals = tickets.map((t) => t.seats * t.price); // [22, 36, 11]
const dune = tickets.filter((t) => t.film === "Dune"); // 2 tickets
const revenue = tickets.reduce((sum, t) => sum + t.seats * t.price, 0); // 69
const big = tickets.find((t) => t.seats >= 4); // the Heat ticket
const anySoldOut = tickets.some((t) => t.seats === 0); // false| Method | Returns | Changes the array? |
|---|---|---|
map | new array, same length | no |
filter | new array, possibly shorter | no |
reduce | one value | no |
find / findIndex | first match / its index (or undefined / -1) | no |
some / every | boolean | no |
push / pop / shift / unshift / splice | various | yes |
sort / reverse | the same array | yes |
Always give reduce a starting value
[].reduce((sum, x) => sum + x); // TypeError: empty array, no initial value
[].reduce((sum, x) => sum + x, 0); // 0The sort() trap
Without a compare function, sort compares elements as strings:
[10, 9, 1].sort(); // [1, 10, 9]
[10, 9, 1].sort((a, b) => a - b); // [1, 9, 10]The compare function returns a negative number if a comes first, positive if b does, and 0 if
they tie. Sorting by several keys chains them with ||:
tickets.sort((a, b) => a.film.localeCompare(b.film) || b.seats - a.seats);sort also mutates the array. If you still need the original, copy first ([...arr].sort())
or use toSorted() (Node.js 20+ and modern browsers).
Grouping and counting
Counting occurrences is a reduce into an object or a Map:
const seatsByFilm = tickets.reduce((acc, t) => {
acc[t.film] = (acc[t.film] ?? 0) + t.seats;
return acc;
}, {});
// { Dune: 3, Heat: 4 }A Map is better when keys aren't strings or when order of insertion matters.
Chaining, and when not to
Chains read well for small data:
const duneRevenue = tickets
.filter((t) => t.film === "Dune")
.map((t) => t.seats * t.price)
.reduce((a, b) => a + b, 0);Each step creates a new array, so for very large arrays a single for...of loop can be faster and
just as clear. Readability first; measure before optimising.
Common mistakes
- Using
mapfor side effects (useforEachorfor...of). - Forgetting to
returninside a multi-line arrow function, which yieldsundefined. - Sorting numbers without a compare function.
These methods appear from JavaScript Fundamentals onwards.
Questions and answers
- Why does [10, 9, 1].sort() return [1, 10, 9]?
- Without a compare function, sort() converts the elements to strings and sorts them alphabetically, so '10' comes before '9'. Pass a compare function: sort((a, b) => a - b).
- Does map change the original array?
- No. map, filter, slice and concat return new arrays. push, pop, splice, sort and reverse change the array in place (sort and reverse also return it). toSorted and toReversed are the non-mutating versions.
Practise it
Read next
- JavaScript equality and type coercion: == vs ===, truthy and falsy
Why 0 == '' is true, which values are falsy, how + turns numbers into strings, and the handful of rules that make JavaScript comparisons predictable.
- JavaScript closures and scope explained with small examples
What a closure is, why let and const are block-scoped while var isn't, the classic loop bug, and how closures give you private state, counters and memoised functions.