JS Array Methods
Arrays come with about three dozen methods. The key split is mutating vs. non-mutating — preferring non-mutating makes state changes obvious.
Non-mutating (return a new array or value)
| Method | Purpose |
|---|---|
map(fn) | Transform each item. |
filter(fn) | Keep items that pass a test. |
reduce(fn, init) | Boil items down to one value. |
slice(start, end) | Sub-range copy. |
concat(arr2) | Combine two arrays. |
join(sep) | Stringify with a separator. |
flat(depth) | Flatten nested arrays. |
flatMap(fn) | map + flat one level. |
toSorted() / toReversed() | Modern non-mutating versions of sort/reverse. |
toSpliced(start, n, …) | Non-mutating splice. |
with(i, val) | Copy with one index replaced. |
Mutating (change the array in place)
| Method | Purpose |
|---|---|
push / pop | Add / remove from the end. |
unshift / shift | Add / remove from the front. |
splice(i, n, …) | Remove n and/or insert at index. |
sort(cmp) | In-place sort. Default is lexicographic. |
reverse() | Reverse in place. |
fill(val, start, end) | Overwrite range with one value. |
Pipeline example
JS
const totals = orders
.filter(o => o.status === "paid")
.map(o => ({ id: o.id, total: o.items.reduce((t, i) => t + i.price * i.qty, 0) }))
.toSorted((a, b) => b.total - a.total)
.slice(0, 10);
Tip: Reach for
toSorted / toReversed over sort / reverse — they don't mutate, so they play nicely with React state, undo stacks, and shared data.Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from JS Array Methods!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Build a new array with each item doubled.
const doubled = nums.
(n => n * 2);
Three letters — transforms each item.
Discussion
Loading…