ā¤ Like
šŸ”– Save
šŸ”— Share
@thedevspaceio
@thedevspaceio

JavaScript Array reduce()

@thedevspaceio

🧮 JavaScript Array reduce() Cheatsheet

reduce() accumulates array values into a single result, making it ideal for summing, grouping, and building new data structures.

āœ… Basic syntax āœ… Don't forget the initial value āœ… Always return the accumulator in the reducer āœ… Summing values āœ… Finding max and min āœ… Counting occurrences

#javascript #arrays #reduce #aggregation #functional #webdev #frontend #coding #tips


reduce() processes each element of an array and accumulates them into a single result via an reducer function.

js
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((acc, n) => acc + n, 0);
 
console.log(sum); // 10

Basic syntax

js
array.reduce((accumulator, element, index, array) => {
  // return updated accumulator
}, initialValue);
ParameterDescription
accumulatorThe value accumulated so far.
elementThe current element being processed.
indexThe index of the current element.
arrayThe original array reduce was called on.
initialValueThe starting value of the accumulator.


Don't forget the initial value

Without an initial value, reduce() uses the first element as the accumulator.

js
const numbers = [1, 2, 3];
const sum = numbers.reduce((acc, n) => acc + n);
console.log(sum); // 6

For empty arrays, this throws a TypeError.

js
const empty = [];
// empty.reduce((acc, n) => acc + n); // TypeError

Always provide an initial value when the array might be empty.

js
const sum = empty.reduce((acc, n) => acc + n, 0);
console.log(sum); // 0

Always return the accumulator in the reducer

Always return the accumulator in the reducer.

js
// āŒ Incorrect: missing return statement
const broken = numbers.reduce((acc, n) => {
  acc + n; // āŒ no return
}, 0);
js
// āœ… Correct: return the updated accumulator
const sum = numbers.reduce((acc, n) => {
  return acc + n; // āœ… return the updated accumulator
}, 0);

Summing values

Add all numbers in an array.

js
const prices = [10, 20, 30];
const total = prices.reduce((sum, price) => sum + price, 0);
 
console.log(total); // 60

Sum a property from objects.

js
const cart = [
  { name: "Apple", price: 1 },
  { name: "Banana", price: 2 },
];
 
const total = cart.reduce((sum, item) => sum + item.price, 0);
console.log(total); // 3

Finding max and min

js
const scores = [45, 82, 67, 91, 55];
 
const max = scores.reduce((acc, score) => (score > acc ? score : acc));
console.log(max); // 91
 
const min = scores.reduce((acc, score) => (score < acc ? score : acc));
console.log(min); // 45

Counting occurrences

js
const fruits = ["apple", "banana", "apple", "orange", "banana"];
 
const counts = fruits.reduce((acc, fruit) => {
  acc[fruit] = (acc[fruit] || 0) + 1;
  return acc;
}, {});
 
console.log(counts);
// { apple: 2, banana: 2, orange: 1 }

Full-Stack AI Developer Roadmap

From HTML & CSS to working with AI models, all in one structured roadmap.

@thedevspaceio
www.thedevspace.io