CodeOath
← All posts
JavaScript65 min total · 16 parts

JavaScript Array and Object Methods Cheat Sheet

Contents — Part 3 of 16: Transforming Arrays
Part 3 of 16 · ~2 min

Transforming Arrays

MethodDoesMutates?Example
.map()Returns a new array built from a callback's return valuesNo[1,2,3].map(x => x * 2)[2,4,6]
.filter()Returns a new array of items that pass a testNo[1,2,3,4].filter(x => x % 2 === 0)[2,4]
.reduce()Folds an array down to a single valueNo[1,2,3].reduce((sum, x) => sum + x, 0)6
.flat(depth)Flattens nested arrays by the given depth (default 1)No[1,[2,[3]]].flat(2)[1,2,3]
.flatMap().map() immediately followed by .flat(1)No[1,2].flatMap(x => [x, x*10])[1,10,2,20]
.sort(compareFn)Sorts in placeYes[3,1,2].sort((a,b) => a - b)[1,2,3]
.reverse()Reverses in placeYes[1,2,3].reverse()[3,2,1]
.slice(start, end)Returns a shallow copy of a portion, original untouchedNo[1,2,3,4].slice(1,3)[2,3]
.splice(start, count, ...items)Removes/inserts elements in place, returns the removed itemsYes[1,2,3].splice(1,1,"x") → returns [2], array becomes [1,"x",3]

.slice() and .splice() are easy to mix up by name alone — .slice() is the safe, non-mutating one that just reads out a portion; .splice() is the one that actually edits the array in place (and can insert, not just remove).

.sort()'s default behavior is a classic trap

With no comparator, .sort() converts every element to a string and sorts lexicographically (character by character) — not numerically:

[1, 2, 10, 21].sort();
// [1, 10, 2, 21] — NOT [1, 2, 10, 21]

As strings, "1" sorts before "10" (a shorter string that's a prefix of a longer one sorts first), "10" sorts before "2" (comparing the first character, '1' < '2'), and "2" sorts before "21" for the same prefix reason — the numeric magnitude of the values never enters into it at all.

[1, 2, 10, 21].sort((a, b) => a - b); // [1, 2, 10, 21] — correct numeric ascending order
[1, 2, 10, 21].sort((a, b) => b - a); // [21, 10, 2, 1] — descending

Always pass an explicit comparator for numbers — (a, b) => a - b for ascending, (a, b) => b - a for descending — never rely on the default for anything other than an array of strings you actually want sorted alphabetically.