Skip to content

JavaScript array methods

Which methods mutate the array and which return a new one matters. Each example logs its result; press Run to try it.

21 entries

Transform (new array)

console.log([1, 2, 3].map((n) => n * 10))

map: same length, transformed.

console.log([1, 2, 3, 4].filter((n) => n > 2))

filter: keep matches.

console.log([[1, 2], [3]].flat(), ["a b", "c"].flatMap((s) => s.split(" ")))

flat / flatMap.

console.log([1, 2, 3, 4].slice(1, 3))

slice(start, end): copy a range.

console.log([1, 2].concat([3], 4))

concat.

const a = [3, 1, 2]
console.log(a.toSorted(), a.toReversed(), a.with(0, 9), a)

ES2023 copying versions; the original stays [3, 1, 2].

Reduce & aggregate

console.log([1, 2, 3].reduce((sum, n) => sum + n, 0))

reduce: fold into one value (always pass an initial value).

const words = ["ant", "bee", "asp"]
console.log(Object.groupBy(words, (w) => w[0]))

Object.groupBy (ES2024).

console.log(Math.max(...[4, 9, 2]))

Max via spread.

Mutating

const a = [1]
a.push(2, 3); a.unshift(0)
console.log(a, a.pop(), a.shift(), a)

push/pop at the end, unshift/shift at the start.

const a = ["a", "b", "c", "d"]
const removed = a.splice(1, 2, "X")
console.log(removed, a)

splice(start, deleteCount, …items).

const n = [10, 9, 1]
n.sort()
console.log(n)
n.sort((a, b) => a - b)
console.log(n)

sort() compares as strings by default; pass a comparator for numbers.

console.log(new Array(3).fill(0), [1, 2, 3].reverse())

fill / reverse.

Create & convert

console.log(Array.from({ length: 5 }, (_, i) => i * i))

Array.from with a mapper.

console.log(Array.from(new Set([1, 1, 2])), [..."héllo"])

Dedupe; split a string into characters.

console.log(Array.isArray([]), [1, 2, 3].join(" | "))

isArray; join.

for (const [i, v] of ["a", "b"].entries()) console.log(i, v)

entries() for index + value.

Frequently asked questions

Which array methods mutate the original array?

push, pop, shift, unshift, splice, sort, reverse, fill and copyWithin mutate. map, filter, slice, concat, flat, toSorted, toReversed, toSpliced and with return new arrays.

Why does [10, 9, 1].sort() give [1, 10, 9]?

Without a comparator, sort converts items to strings and compares them in UTF-16 order. Use sort((a, b) => a - b) for numbers.

forEach or for…of?

for…of supports break, continue and await; forEach does not. Use map or filter when you are building a new array.

Related cheat sheets