← Back to Concepts

Array Reduce

Array Reduce: No initial value

We use reduce to reduce array of strings into a single string (concatenates all strings). When we don't have an initial value, the first element is used as the initial value. Reduce starts from the second element and applies the callback function to each element.

const words = ["I", "love", "JS"];
const sentence = words.reduce(
    (accumulator, word) => {
        return accumulator + " " + word;
    }
);

Key Points:

  • First element becomes accumulator: When no initial value is provided, the first array element automatically becomes the starting accumulator value
  • Iteration starts from second element: Reduce begins processing from index 1, not index 0
  • Transformation pattern: Demonstrates how reduce can transform an array into a single accumulated value (strings → sentence)
  • Accumulator updates: Shows how the accumulator value grows with each iteration

Array Reduce: with initial value

We use reduce to count how many even numbers are in the array. Uses an initial value of 0 as we start counting from 0. Because we have initital value, reduce starts from the first element.

const numbers = [2, 5, 10, 7, 2];
const evenCount = numbers.reduce(
    (count, num) => {
        if (num % 2 === 0) {
            return count + 1;
        } else {
            return count;
        }
    },
    0
);

Key Points:

  • Explicit initial value: When an initial value is provided (e.g., 0), the accumulator starts with that value
  • Iteration starts from first element: Reduce processes all elements starting from index 0
  • Conditional accumulator updates: Demonstrates using if/else logic to conditionally ignore elements that don't meet the criteria
  • Counting pattern: Shows how reduce can be used for counting elements that meet specific criteria