Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Reducing Arrays with reduce | Advanced Array Manipulation
JavaScript Array Methods

bookReducing Arrays with reduce

123
const numbers = [10, 20, 30, 40]; const sum = numbers.reduce((accumulator, current) => accumulator + current, 0); console.log(sum); // Output: 100
copy
123456789101112131415
const items = [ { name: "apple", type: "fruit" }, { name: "carrot", type: "vegetable" }, { name: "banana", type: "fruit" }, { name: "celery", type: "vegetable" } ]; const grouped = items.reduce((acc, item) => { if (!acc[item.type]) { acc[item.type] = []; } acc[item.type].push(item.name); return acc; }, {}); console.log(JSON.stringify(grouped)); // Output: { fruit: ["apple", "banana"], vegetable: ["carrot", "celery"] }
copy

How reduce Works Step by Step

  1. The reduce method loops through the array from the first element to the last;
  2. On each iteration, it calls the callback function with two main arguments: the accumulator (which stores the ongoing result) and the current value (the current array item);
  3. The first time the callback runs, the accumulator is set to the initial value you provide (if omitted, it defaults to the first array element);
  4. The callback returns a new value for the accumulator, which is used in the next iteration;
  5. After the last item, reduce returns the final value of the accumulator.

For example, when summing numbers, the accumulator starts at 0, and each number is added in turn. When grouping objects, the accumulator might start as an empty object, and each object is added to a group based on a property.

Common Pitfalls and Best Practices with reduce

When using reduce, there are some common pitfalls to avoid:

  • Forgetting to set an initial value can cause unexpected results, especially with empty arrays;
  • The accumulator's type should match the final result you want—use 0 for sums, {} for objects, or [] for arrays;
  • Avoid making your callback too complex. If your logic is hard to follow, consider using other array methods or breaking your callback into smaller functions;
  • Always double-check that your callback returns the accumulator value on each iteration.

Following these best practices helps you write clear, reliable code with reduce.

1. Which scenario is the best fit for using reduce?

2. Complete the reduce callback to count how many times each color appears in the array.

question mark

Which scenario is the best fit for using reduce?

Select the correct answer

question-icon

Complete the reduce callback to count how many times each color appears in the array.

const colors = ["red", "blue", "red", "green", "blue", "red"]; const colorCount = colors.reduce((acc, color) => { return acc; }, {}); console.log(colorCount); // { red: 3, blue: 2, green: 1 }
{ red: 3, blue: 2, green: 1 }

Click or drag`n`drop items and fill in the blanks

Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 3. Kapitel 3

Spørg AI

expand

Spørg AI

ChatGPT

Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat

Awesome!

Completion rate improved to 8.33

bookReducing Arrays with reduce

Stryg for at vise menuen

123
const numbers = [10, 20, 30, 40]; const sum = numbers.reduce((accumulator, current) => accumulator + current, 0); console.log(sum); // Output: 100
copy
123456789101112131415
const items = [ { name: "apple", type: "fruit" }, { name: "carrot", type: "vegetable" }, { name: "banana", type: "fruit" }, { name: "celery", type: "vegetable" } ]; const grouped = items.reduce((acc, item) => { if (!acc[item.type]) { acc[item.type] = []; } acc[item.type].push(item.name); return acc; }, {}); console.log(JSON.stringify(grouped)); // Output: { fruit: ["apple", "banana"], vegetable: ["carrot", "celery"] }
copy

How reduce Works Step by Step

  1. The reduce method loops through the array from the first element to the last;
  2. On each iteration, it calls the callback function with two main arguments: the accumulator (which stores the ongoing result) and the current value (the current array item);
  3. The first time the callback runs, the accumulator is set to the initial value you provide (if omitted, it defaults to the first array element);
  4. The callback returns a new value for the accumulator, which is used in the next iteration;
  5. After the last item, reduce returns the final value of the accumulator.

For example, when summing numbers, the accumulator starts at 0, and each number is added in turn. When grouping objects, the accumulator might start as an empty object, and each object is added to a group based on a property.

Common Pitfalls and Best Practices with reduce

When using reduce, there are some common pitfalls to avoid:

  • Forgetting to set an initial value can cause unexpected results, especially with empty arrays;
  • The accumulator's type should match the final result you want—use 0 for sums, {} for objects, or [] for arrays;
  • Avoid making your callback too complex. If your logic is hard to follow, consider using other array methods or breaking your callback into smaller functions;
  • Always double-check that your callback returns the accumulator value on each iteration.

Following these best practices helps you write clear, reliable code with reduce.

1. Which scenario is the best fit for using reduce?

2. Complete the reduce callback to count how many times each color appears in the array.

question mark

Which scenario is the best fit for using reduce?

Select the correct answer

question-icon

Complete the reduce callback to count how many times each color appears in the array.

const colors = ["red", "blue", "red", "green", "blue", "red"]; const colorCount = colors.reduce((acc, color) => { return acc; }, {}); console.log(colorCount); // { red: 3, blue: 2, green: 1 }
{ red: 3, blue: 2, green: 1 }

Click or drag`n`drop items and fill in the blanks

Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 3. Kapitel 3
some-alt