Cheatsheet

JavaScript Array Methods Cheatsheet

This sheet lists the methods on Array.prototype and the static Array functions, with the signature, the return value and whether each one changes the original array. It is for developers who keep forgetting whether sort copies, what splice returns, or when to reach for toSorted. The confusion it clears up: a few old methods mutate in place, and the newer to* and with methods return a copy.

Quick reference

Mutating vs non-mutating

Method Mutates Returns
`push(...items)` yes New length
`pop()` yes Removed last item
`unshift(...items)` yes New length
`shift()` yes Removed first item
`splice(start, deleteCount, ...items)` yes Array of removed items
`sort(compareFn)` yes The same array
`reverse()` yes The same array
`fill(value, start, end)` yes The same array
`copyWithin(target, start, end)` yes The same array
`slice(start, end)` no New array
`concat(...values)` no New array
`toSorted(compareFn)` no New sorted array
`toReversed()` no New reversed array
`toSpliced(start, deleteCount, ...items)` no New array
`with(index, value)` no New array with one item replaced

Search and test

Method Returns Not found
`includes(value, from)` boolean `false`
`indexOf(value, from)` index `-1`
`lastIndexOf(value, from)` index `-1`
`find(fn)` first matching item `undefined`
`findIndex(fn)` index of first match `-1`
`findLast(fn)` last matching item `undefined`
`findLastIndex(fn)` index of last match `-1`
`some(fn)` true if any item passes `false` (also for `[]`)
`every(fn)` true if all items pass `true` for `[]`
`at(index)` item, negative counts from end `undefined`

Transform and iterate

Method Returns Callback arguments
`map(fn)` new array, same length `(value, index, array)`
`filter(fn)` new array of items that pass `(value, index, array)`
`forEach(fn)` `undefined` `(value, index, array)`
`reduce(fn, initial)` accumulated value `(acc, value, index, array)`
`reduceRight(fn, initial)` accumulated value, right to left `(acc, value, index, array)`
`flat(depth)` new array, default depth 1 none
`flatMap(fn)` map then flat by one level `(value, index, array)`
`join(separator)` string, default separator `,` none
`keys()`, `values()`, `entries()` iterators none

The callback methods all take an optional second argument that becomes this inside a non-arrow callback. They skip empty slots in sparse arrays, and the length is fixed before the loop starts, so items pushed during a loop are not visited. Arrow functions are the usual choice, which makes that argument rarely needed.

Static functions

Function Use
`Array.isArray(x)` Reliable array check, `typeof []` is `object`
`Array.from(iterable, mapFn)` Convert iterables and array-likes
`Array.of(...items)` Build from arguments, `Array.of(3)` is `[3]`
`Array.fromAsync(iterable)` Like `from`, awaits async iterables and promises

When each newer method became widely available

Method Available across browsers since
`includes` August 2016
`flat`, `flatMap` January 2020
`at` March 2022
`findLast`, `findLastIndex` August 2022
`toSorted`, `toReversed`, `toSpliced`, `with` July 2023

Dates come from MDN's Baseline notes. Check the targets in your own support policy before using the newest ones.

Common patterns

Sort numbers, not strings

console.log([10, 9, 80, 1].sort());
console.log([10, 9, 80, 1].sort((x, y) => x - y));
[ 1, 10, 80, 9 ]
[ 1, 9, 10, 80 ]

Without a compare function, items are converted to strings and sorted by UTF-16 code unit order. The sort has been stable since ECMAScript 2019, so equal items keep their order. Numeric and date arrays both need an explicit compare function.

Sort without changing the original

const orig = [3, 1, 2];
const s = orig.toSorted();
console.log(orig, s);
const m = [3, 1, 2];
console.log(m.sort() === m);
[ 3, 1, 2 ] [ 1, 2, 3 ]
true

sort returns the same array it changed. Use toSorted, or [...arr].sort() on older runtimes.

Remove, insert and replace with splice

const sp = [1, 2, 3, 4, 5];
console.log(sp.splice(1, 2, 'a', 'b', 'c'), sp);
console.log([1, 2, 3, 4].toSpliced(1, 2, 'x'));
console.log([1, 2, 3].with(1, 'b'), [1, 2, 3].with(-1, 9));
[ 2, 3 ] [ 1, 'a', 'b', 'c', 4, 5 ]
[ 1, 'x', 4 ]
[ 1, 'b', 3 ] [ 1, 2, 9 ]

splice returns what it removed, not the array. Use it for in-place edits, and toSpliced or with for immutable updates.

Flatten and expand

console.log([1, [2, [3, [4]]]].flat());
console.log([1, [2, [3, [4]]]].flat(Infinity));
console.log(['a b', 'c'].flatMap(x => x.split(' ')));
[ 1, 2, [ 3, [ 4 ] ] ]
[ 1, 2, 3, 4 ]
[ 'a', 'b', 'c' ]

flat goes one level deep unless you pass a depth. flatMap is map followed by a one-level flat.

Sum, dedupe, chunk and group

console.log([1, 2, 3].reduce((s, x) => s + x, 0));
console.log([...new Set([1, 2, 2, 3, 1])]);
console.log(Array.from({length: 3}, (_, i) => [1, 2, 3, 4, 5, 6, 7].slice(i * 3, i * 3 + 3)));
console.log(Object.groupBy([1, 2, 3, 4, 5], x => x % 2 ? 'odd' : 'even'));
6
[ 1, 2, 3 ]
[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7 ] ]
[Object: null prototype] { odd: [ 1, 3, 5 ], even: [ 2, 4 ] }

Grouping is Object.groupBy, a static function on Object, not an array method.

Build arrays from other things

console.log(Array.from({length: 3}, (_, i) => i * 2), Array.from('abc'));
console.log(Array.from(new Set([1, 1, 2])), [...Array(3).keys()]);
console.log([...['a', 'b'].entries()]);
[ 0, 2, 4 ] [ 'a', 'b', 'c' ]
[ 1, 2 ] [ 0, 1, 2 ]
[ [ 0, 'a' ], [ 1, 'b' ] ]

Sort strings with accents and mixed case

console.log(['b', 'a', 'Z', 'é'].sort());
console.log(['b', 'a', 'Z', 'é'].sort((x, y) => x.localeCompare(y)));
[ 'Z', 'a', 'b', 'é' ]
[ 'a', 'b', 'é', 'Z' ]

The default sort puts every uppercase letter before every lowercase letter, and accented letters last. localeCompare sorts the way a reader expects.

Sort objects by a field and keep ties in order

const o = [{n: 'a', g: 2}, {n: 'b', g: 1}, {n: 'c', g: 2}];
console.log(o.sort((p, q) => p.g - q.g).map(x => x.n).join(''));
bac

Items a and c tie on g, and a stays ahead of c because the sort is stable. Subtracting only works for numbers, so use localeCompare for text fields.

Take a slice from either end

console.log([1, 2, 3, 4, 5].slice(1, 3), [1, 2, 3, 4, 5].slice(-2));
console.log([1].concat([2], [[3]], 4));
console.log([1, [2, 3], null, undefined].join('-'));
[ 2, 3 ] [ 4, 5 ]
[ 1, 2, [ 3 ], 4 ]
1-2,3--

slice excludes the end index and accepts negative numbers. concat spreads one level of array arguments only, and join turns null and undefined into empty strings.

Pitfalls

  • Comparing with a boolean in sort: (a, b) => a > b returns true or false, not a negative or positive number. In Node 22, [3, 1, 2, 10, 5].sort((a, b) => a > b) returned [ 3, 1, 2, 10, 5 ], unsorted. Return a - b.
  • Passing parseInt straight to map: map passes the index as the second argument, which parseInt reads as the radix. ['1','2','3'].map(parseInt) gives [ 1, NaN, NaN ]. Use map(Number).
  • Reducing an empty array without an initial value: [].reduce((s, x) => s + x) throws TypeError: Reduce of empty array with no initial value. Always pass the second argument.
  • Using indexOf to find NaN: [NaN].indexOf(NaN) is -1, while [NaN].includes(NaN) is true. Use includes for existence checks.
  • Filling with a shared object: new Array(2).fill([]) puts the same array reference in both slots, so a push to one shows in the other. Use Array.from({length: 2}, () => []).
  • Reading arr[-1]: it is undefined, because -1 is a property name, not an index. Use at(-1).
  • Shallow copies: [...arr], slice() and toSorted() copy the outer array only. Objects inside are shared, so editing copy[0].id also changes the original. Use structuredClone for deep copies.
  • Assuming every and some need items: [].every(x => false) is true and [].some(x => true) is false, so an empty list passes a validation built on every. Check length first.
  • Expecting forEach to return something or stop early: it returns undefined and cannot be broken out of. Use a for...of loop, or some and every for early exit.
  • Holes from delete and Array(3): delete x[1] leaves an empty slot and keeps length, and forEach and map skip empty slots. Use splice to remove an item.

Related ZipKit tools

Related cheatsheets