console.log([1, 2, 3].map((n) => n * 10))map: same length, transformed.
Which methods mutate the array and which return a new one matters. Each example logs its result; press Run to try it.
21 entries
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].
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.
const users = [{ id: 1, n: "a" }, { id: 2, n: "b" }]
console.log(users.find((u) => u.id === 2), users.findIndex((u) => u.id === 2))find / findIndex.
console.log([1, 2, 3].findLast((n) => n < 3))findLast / findLastIndex.
console.log([1, 2, NaN].includes(NaN), [1, 2].indexOf(2))includes handles NaN; indexOf does not.
console.log([2, 4].every((n) => n % 2 === 0), [1, 2].some((n) => n > 1))every / some.
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.
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.
push, pop, shift, unshift, splice, sort, reverse, fill and copyWithin mutate. map, filter, slice, concat, flat, toSorted, toReversed, toSpliced and with return new arrays.
Without a comparator, sort converts items to strings and compares them in UTF-16 order. Use sort((a, b) => a - b) for numbers.
for…of supports break, continue and await; forEach does not. Use map or filter when you are building a new array.