elefcode
← All cheat sheets

Languages

JavaScript Array Methods Cheat Sheet

Array methods grouped by what they do, with a note on whether each one changes the original array.

Put it into practice with the matching tool.

Format JSON

Advertisement

Adding & removing

push(x)Add to the end — mutates
pop()Remove the last item — mutates
unshift(x)Add to the start — mutates
shift()Remove the first item — mutates
splice(i, n, ...items)Remove/insert at an index — mutates
slice(start, end)Copy a portion — does not mutate
concat(arr)Join arrays into a new one

Transforming

map(fn)New array with each item transformed
filter(fn)New array with only items that pass the test
reduce(fn, init)Collapse the array into a single value
flat(depth)Flatten nested arrays
flatMap(fn)Map then flatten one level
join(sep)Combine into a string

Searching

find(fn)First item matching the test (or undefined)
findIndex(fn)Index of the first match (or -1)
findLast(fn)Last item matching the test
indexOf(x)Index of a value (or -1)
includes(x)True if the value exists

Testing & iterating

forEach(fn)Run a function for each item (returns undefined)
some(fn)True if at least one item passes
every(fn)True if all items pass
Array.isArray(x)Check whether a value is an array

Ordering

sort((a,b) => a - b)Sort numerically — mutates
sort()Sorts as strings by default (10 before 2)
reverse()Reverse in place — mutates
toSorted() / toReversed()Newer non-mutating versions

Creating

Array.from(x)Build an array from an iterable or array-like
Array.from({length: 5}, (_, i) => i)Generate [0,1,2,3,4]
Array.of(1, 2)Create an array from arguments
[...new Set(arr)]Remove duplicates

More cheat sheets