Javascript in 100 bits

Course by zooboole,

Last Updated on 2025-01-28 08:04:00

Lesson 35 - JavaScript Array Method – reduce()

The reduce() method processes an array and reduces it to a single value, like a sum or product.

Explanation

  • The method applies a callback function to each element.
  • It accumulates values based on the function.
  • It returns a single result (e.g., total sum, max value, concatenated string).

Syntax

array.reduce((accumulator, element, index, array) => {
    return newAccumulatorValue;
}, initialValue);
  • accumulator: Stores the accumulated result.
  • element: The current item being processed.
  • index (optional): The index of the current element.
  • array (optional): The array being reduced.
  • initialValue (optional): The starting value for the accumulator.

Example 1: Sum of Numbers

let numbers = [1, 2, 3, 4, 5];

let sum = numbers.reduce((acc, num) => acc + num, 0);

console.log(sum); // Output: 15
  • Adds up all numbers in the array.

Example 2: Finding Maximum Value

let numbers = [3, 7, 2, 9, 5];

let maxNumber = numbers.reduce((max, num) => (num > max ? num : max), numbers[0]);

console.log(maxNumber); // Output: 9
  • Finds the largest number.

Example 3: Counting Occurrences

let words = ["apple", "banana", "apple", "orange", "banana", "apple"];

let wordCount = words.reduce((acc, word) => {
    acc[word] = (acc[word] || 0) + 1;
    return acc;
}, {});

console.log(wordCount); 
// Output: { apple: 3, banana: 2, orange: 1 }
  • Counts occurrences of words in an array.

Try Your Hand

Steps:

  1. Create a File:

    • Name it lesson35-reduce.html.
  2. Write the Code:

    • Copy the following:

      <!DOCTYPE html>
      <html lang="en">
      <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Lesson 35 - reduce() Method</title>
      </head>
      <body>
      <h2>Sum of Numbers</h2>
      <p id="result"></p>
      
      <script>
         let numbers = [10, 20, 30, 40];
      
         let total = numbers.reduce((sum, num) => sum + num, 0);
      
         document.getElementById("result").textContent = "Total Sum: " + total;
      </script>
      </body>
      </html>
  3. Save the File.

  4. Open it in a Browser to See the Sum.


Experiment

  1. Multiply all numbers in an array using reduce().
  2. Find the longest word in an array of strings.
  3. Flatten a nested array into a single array.

Key Takeaways

  • reduce() transforms an array into a single value.
  • It can be used for math operations, object accumulation, and data processing.
  • Useful for summation, filtering, counting, and merging data.