Ayan

WritingMost Used JS Array Methods

2 min read

Most Used JS Array Methods

A practical tour of the array methods you will reach for daily: map, filter, reduce, find, some, every, and friends, with the pitfalls that bite in real code.

Placeholder intro. Arrays are the most common data structure in everyday JavaScript, and a handful of methods cover about 90% of what you will do with them.

Transforming: map

map returns a new array of the same length, with each element passed through a function.

const prices = [10, 20, 30];
const withTax = prices.map((p) => p * 1.18);
// [11.8, 23.6, 35.4]

Failure mode: using map for side effects only. If you ignore the returned array, use forEach.

Selecting: filter

filter returns a new array containing only elements for which the callback returns a truthy value.

const users = [
  { name: "Asha", active: true },
  { name: "Ravi", active: false },
];
const activeUsers = users.filter((u) => u.active);

Aggregating: reduce

reduce folds an array into a single value: a number, object, or even another array.

const total = [1, 2, 3, 4].reduce((sum, n) => sum + n, 0);
// 10

Failure mode: omitting the initial value. On an empty array this throws a TypeError.

Searching: find, findIndex, includes

const nums = [5, 12, 8, 130];
nums.find((n) => n > 10);      // 12
nums.findIndex((n) => n > 10); // 1
nums.includes(8);              // true

find returns undefined when nothing matches, so always handle that case.

Testing: some and every

const ages = [18, 21, 35];
ages.some((a) => a < 18);  // false
ages.every((a) => a >= 18); // true

Both short-circuit, so they stop iterating as soon as the answer is known.

Flattening: flat and flatMap

[[1, 2], [3, [4]]].flat();      // [1, 2, 3, [4]]
[[1, 2], [3, [4]]].flat(2);     // [1, 2, 3, 4]
["a b", "c d"].flatMap((s) => s.split(" ")); // ["a", "b", "c", "d"]

Sorting: sort (handle with care)

[10, 9, 1].sort();            // [1, 10, 9] (string comparison!)
[10, 9, 1].sort((a, b) => a - b); // [1, 9, 10]

Failure mode: sort mutates the original array and defaults to lexicographic order. Prefer toSorted (ES2023) or copy first with [...arr].sort(...).

Mutating vs non-mutating

Mutates the original Returns a new array
push, pop map, filter
splice, sort slice, concat
reverse toSorted, toReversed

Chaining

const result = orders
  .filter((o) => o.status === "paid")
  .map((o) => o.amount)
  .reduce((sum, a) => sum + a, 0);

Wrap-up

Placeholder conclusion. Reach for map, filter, and reduce first, know which methods mutate, and watch the sort default.

Back to all writing