Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript Array Methods: map, filter, reduce and More

Array methods are essential for transforming and processing data in modern JavaScript applications.

Why this matters

Clean array operations improve readability, reduce loop bugs, and accelerate feature development.

Transformation vs Selection vs Aggregation

Use map to transform each element into new form.

Use filter to keep only matching elements.

Use reduce for aggregated output such as totals, grouped objects, or summary metrics.

Searching and Sorting Patterns

Use find for first match, filter for all matches, and includes for simple primitive presence checks.

sort mutates arrays. Clone with spread before sorting when immutability matters.

Code Examples

Pipeline with map/filter/reduce

const orders = [
  { id: 1, amount: 500, paid: true },
  { id: 2, amount: 1200, paid: false },
  { id: 3, amount: 750, paid: true },
];

const paidTotal = orders
  .filter((o) => o.paid)
  .map((o) => o.amount)
  .reduce((sum, amt) => sum + amt, 0);

console.log(paidTotal);

A standard business logic flow in dashboards and reports.

find vs filter

const products = [
  { sku: "A1", stock: 0 },
  { sku: "B2", stock: 12 },
  { sku: "C3", stock: 5 },
];

console.log(products.find((p) => p.stock > 0));
console.log(products.filter((p) => p.stock > 0));

find gives first match; filter gives full list.

Immutable Sort

const nums = [9, 2, 6, 1];
const sorted = [...nums].sort((a, b) => a - b);
console.log(nums);   // original intact
console.log(sorted);

Clone first to avoid mutating source array.

Common Mistakes and Fixes

Using map for side effects

Use forEach for side effects; reserve map for returned transformed arrays.

No initial value in reduce

Pass explicit initial accumulator for predictable behavior.

Mutating source array unexpectedly

Clone before using sort/splice when immutable behavior is required.

Frequently Asked Questions

Is reduce better than loops?

Use whichever is clearer. reduce is powerful but should remain readable.

Does sort always mutate array?

Yes, native sort mutates. Clone first if you need original preserved.

Should I chain many methods in one line?

Only while readable. Break into named steps when logic grows complex.

Which array methods are most asked in interviews?

map, filter, reduce, find, sort, and flat/flatMap are frequently discussed.

Related JavaScript Topics