JavaScriptArraysIterationData Processing

JavaScript Array Methods: map, splice, sort, and for...of

Choose JavaScript array methods by mutation, return value, early exit, async behavior, and readability: map, filter, reduce, find, slice, splice, sort, toSorted, and for...of.

·Updated ·13 min read·Counting...
JavaScript Array Methods: map, splice, sort, and for...of

When choosing a JavaScript array API, ask two questions first: do you want a new array or do you want to mutate the existing one? Do you need early exit or sequential await? map, filter, and slice return new arrays. splice, sort, and reverse mutate the array. When you need break, continue, or sequential async work, use for...of.

Mutating vs non-mutating methods

Returns new value or arrayMutates the original array
map, filter, slice, concatpush, pop, shift, unshift
toSorted, toReversed, toSplicedsort, reverse, splice
find, some, every, reducefill, copyWithin

In React state, reducers, and data pipelines, prefer non-mutating methods unless mutation is deliberate and local.

Add and remove items

CODE
const tools = ["Raycast", "IINA"]

tools.push("AppCleaner")
const last = tools.pop()

Those methods modify tools. To keep the original array unchanged:

CODE
const withBrew = [...tools, "Homebrew"]
const withoutIINA = tools.filter((tool) => tool !== "IINA")

This matters when references are used to detect updates.

slice vs splice

slice(start, end) returns a new array for the half-open range [start, end):

CODE
const values = [0, 1, 2, 3, 4]
values.slice(1, 4) // [1, 2, 3]
values             // [0, 1, 2, 3, 4]

splice(start, deleteCount, ...items) mutates the array and returns removed items:

CODE
const values = ["a", "b", "c"]
const removed = values.splice(1, 1, "B", "B2")

removed // ["b"]
values  // ["a", "B", "B2", "c"]

Modern runtimes also provide toSpliced for a non-mutating version:

CODE
const next = values.toSpliced(1, 1, "new")

map, filter, and reduce

Use map to transform each item:

CODE
const names = tools.map((tool) => tool.name)

Use filter to keep items that match a condition:

CODE
const freeTools = tools.filter((tool) => tool.price === 0)

Use reduce to collapse a list into one result:

CODE
const total = cart.reduce((sum, item) => sum + item.price * item.quantity, 0)

If the reducer callback needs many comments, a plain loop may be clearer. Do not compress business logic into reduce just to look functional.

find, some, and every

CODE
const iina = tools.find((tool) => tool.slug === "iina")
const hasFreeTool = tools.some((tool) => tool.price === 0)
const allAvailable = tools.every((tool) => tool.available)
  • find returns the first matching item or undefined.
  • some stops once it finds true.
  • every stops once it finds false.

If you only need an existence check, do not filter the whole array and then check .length.

sort and toSorted

sort mutates the original array, and its default comparison is string-based:

CODE
[10, 2, 30].sort() // [10, 2, 30]

For numeric sorting:

CODE
const ascending = numbers.toSorted((a, b) => a - b)

If toSorted is unavailable:

CODE
const ascending = [...numbers].sort((a, b) => a - b)

Comparison functions should be stable and deterministic. Avoid random comparison functions.

for, forEach, for...of, and for...in

Use for when you need indexes, exact stepping, or two-pointer logic:

CODE
for (let index = 0; index < items.length; index += 1) {
  if (items[index].hidden) continue
  render(items[index])
}

Use forEach for simple synchronous side effects, but remember that you cannot break and it does not await async callbacks:

CODE
items.forEach((item) => console.log(item.id))

Use for...of for iterables, early exit, and sequential async work:

CODE
for (const item of items) {
  if (!item.valid) break
  await save(item)
}

for...in iterates enumerable string property names and is not the right default for arrays.

Quick selection table

NeedUse
Transform each itemmap
Keep matching itemsfilter
Find the first itemfind
Check whether any item matchessome
Aggregate into one resultreduce or a clear loop
Copy a rangeslice
Insert or remove in placesplice
Need break, continue, or sequential awaitfor...of
Need index controlfor

Subscribe to FreeMac

Weekly picks: free Mac software reviews, trusted source updates, alternatives, and low-friction guides.