JavaScript Array Reduce Method

Facebook logoTwitter logoLinkedin logo
image contains "JavaScript Array Reduce Method" text and vectors

The JavaScript reduce method is a powerful array method that allows you to reduce the elements of an array into a single output value.

Syntax

array.reduce(callback, initialValue)
Copy

callback Parameters

function callback(accumulator, currentValue, currentIndex, array) {}
Copy

Parameters

  • callback: This is a function that is called for each element in the array. It takes four arguments:

    1. accumulator: The accumulated result of the previous iterations or the initial value if provided.
    2. currentValue: The current element being processed in the array.
    3. currentIndex (optional): The index of the current element being processed.
    4. array (optional): The array reduce() was called upon.
  • initialValue (optional): This is the initial value of the accumulator. If it's not provided, the first element of the array is used as the initial accumulator value, and the iteration starts from the second element.

Return Value

The Array.reduce() method in JavaScript returns the final accumulated result after iterating through all the elements of the array, applying the callback function to each element.

Here's how the return value of the Array.reduce() method works:

Without an Initial Value: If you don't provide an initial value as the second argument to reduce(), the return value will be the final accumulated value after processing all elements. For example:

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

const sum = numbers.reduce((accumulator, currentValue) => {
  return accumulator + currentValue;
});

console.log(sum); // Output: 15
Copy

In this case, the return value of sum will be 15, which is the result of adding all elements together.

With an Initial Value: If you provide an initial value as the second argument to reduce(), the return value will be the final accumulated value after processing all elements, starting with the initial value. For example:

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

const sum = numbers.reduce((accumulator, currentValue) => {
  return accumulator + currentValue;
}, 1);

console.log(sum); // Output: 16
Copy

So, in summary, the return value of Array.reduce() is the final result of the accumulation process, whether you provide an initial value or not.

Examples

Calculating the total values in an array

const numbers = [10, 40, 50];

const total = numbers.reduce((accumulator, currentValue) => {
  return accumulator + currentValue;
}, 0);

console.log(total); // Output: 100
Copy

Finding minimum and maximum values

const numbers = [10, 5, 8, 20, 2, 16];

// Finding the minimum value
const min = numbers.reduce((minValue, currentValue) => {
  return Math.min(minValue, currentValue);
}, numbers[0]); // Initialize minValue with the first element of the array

// Finding the maximum value
const max = numbers.reduce((maxValue, currentValue) => {
  return Math.max(maxValue, currentValue);
}, numbers[0]); // Initialize maxValue with the first element of the array

console.log(`Minimum value: ${min}`);
console.log(`Maximum value: ${max}`);
Copy

Finding averages

// Sample array of numbers
const numbers = [10, 20, 30, 40, 50];

// Use reduce to find the sum of all numbers
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);

// Calculate the average by dividing the sum by the number of elements
const average = sum / numbers.length;

console.log("Sum:", sum);
console.log("Average:", average);
Copy

Remove Duplicate Items in an Array With JavaScript Reduce

const array = ["a","a","b","b","c","c"];

const uniqueArray = array.reduce((accumulator, currentValue) => {
  if (!accumulator.includes(currentValue)) {
    accumulator.push(currentValue);
  }
  return accumulator;
}, []);

console.log(uniqueArray); // Output: ['a', 'b', 'c']
Copy

To learn more about Array.includes(), check out this article I wrote recently here

Flatten Arrays with JavaScript Reduce

function flattenArray(arr) {
  return arr.reduce((acc, current) => {
    // Check if the current element is an array
    if (Array.isArray(current)) {
      // If it's an array, recursively call flattenArray
      // and concatenate the result with the accumulator
      return acc.concat(flattenArray(current));
    } else {
      // If it's not an array, simply add it to the accumulator
      return acc.concat(current);
    }
  }, []);
}

const nestedArray = [1, 2, [3, 4, [5, 6]], 7, [8]];

const flattenedArray = flattenArray(nestedArray);

console.log(flattenedArray); // Output: [1, 2, 3, 4, 5, 6, 7, 8]
Copy

In the flattenArray function, we use the reduce method to iterate through the elements of the input array (arr). For each element, we check if it's an array or not. If it's an array, we recursively call flattenArray on that element and concatenate the result with the accumulator (acc). If it's not an array, we simply add it to the accumulator.

Using reduce() on array of objects

const products = [
  { name: 'Product 1', price: 10 },
  { name: 'Product 2', price: 20 },
  { name: 'Product 3', price: 30 }
];

const totalPrice = products.reduce((accumulator, product) => {
  return accumulator + product.price;
}, 0);

console.log(totalPrice); // Output: 60
Copy

Practical tips to advance your skills

  • Understand the basics.
  • Start with simple examples.
  • Master the callback function.
  • Always initialize the accumulator.
  • Aim for immutable operations.
  • Consider error handling.
  • Use debugging techniques.
  • Learn to chain methods.
  • Embrace functional programming.
  • Practice with real data.
  • Explore various use cases.
  • Be mindful of performance.
  • Consult documentation and resources.
  • Collaborate and review code.
  • Experiment and explore creatively.
  • Refactor code to use reduce().

Browser Support

The reduce method is widely supported you can use it freely without worrying about Browser Support, for in-depth details check out the can I use site

Conclusion

The reduce() method in JavaScript is a powerful tool for working with arrays. It allows you to perform complex operations while keeping your code clean and concise.

By understanding how reduce() works and practicing with different use cases, you can become a more proficient JavaScript developer. So, the next time you face a problem involving array manipulation, consider using the reduce() method to simplify your code and make it more efficient. Happy coding!