JavaScript by Example

Array Transforms

map, filter, and reduce turn arrays into new values without mutating the original list.

Array transforms let you describe what should happen to each item instead of manually pushing into a result array.

map transforms each element into a new value and returns a new array. filter keeps elements that pass a predicate, which is a function that returns true or false. Neither mutates the original.

const prices = [10, 25, 8, 40, 15];
 
const doubled = prices.map((p) => p * 2);
console.log(doubled); // [20, 50, 16, 80, 30]
 
const affordable = prices.filter((p) => p < 20);
console.log(affordable); // [10, 8, 15]
 
console.log(prices); // unchanged

reduce accumulates elements into one value, such as a sum, object, or array. Always provide the initial accumulator so empty arrays behave predictably.

const orders = [
  { product: "book", qty: 2, price: 12 },
  { product: "pen", qty: 5, price: 1.5 },
  { product: "desk", qty: 1, price: 200 },
];
 
const total = orders.reduce((sum, o) => sum + o.qty * o.price, 0);
console.log(total); // 231.5

In production

Prefer map and filter when each input item maps cleanly to output. Reach for reduce when the result is not one item per input, such as a total or grouped object. If reduce gets hard to read, a plain loop is often better.

Enjoyed this? Get more software craft delivered to your inbox.