Sharing is caring 🙂

The reduce() method is a higher-order function that applies a callback function to an accumulator and each element in an array (from left to right) in order to reduce the array to a single value. It is called reduce because it reduces an array to a single value. Here is the syntax for the reduce() method:

arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])

The callback function takes four arguments:

  • accumulator: This is the accumulator that stores the accumulated value. It is the result of the previous callback call, or the initial value if no previous call exists.
  • currentValue: This is the current element being processed in the array.
  • index (optional): This is the index of the current element being processed in the array.
  • array (optional): This is the array the reduce() method was called upon.

The initialValue (optional) is the initial value of the accumulator. If no initial value is provided, the first element in the array will be used as the accumulator, and the callback function will start processing from the second element.

Here is an example of using the reduce() method to sum the elements of an array:

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

const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);

console.log(sum); // Output: 10

In this example, the callback function takes two arguments: the accumulator and the currentValue. The initialValue is set to 0. The callback function adds the accumulator and the currentValue and stores the result in the accumulator. The callback function is called for each element in the numbers array, starting with the first element and the initialValue of 0. The final result of the reduce() method is the sum of all the elements in the numbers array.

The reduce() method is a powerful tool for processing and transforming arrays, and it can perform a wide variety of operations on arrays. It is often used in combination with other array methods such as map(), filter(), and sort() to create complex and flexible array processing pipelines.

Using the JavaScript reduce method to sum an array of numbers

To use the reduce() method to sum an array of numbers, you can pass a callback function that takes two arguments: the accumulator and the currentValue, and returns the sum of these two values. The initialValue can be set to 0 to start the sum at 0, or to any other value to start the sum at that value.

Here is an example of using the reduce() method to sum an array of numbers:

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

const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);

console.log(sum); // Output: 10

In this example, the callback function takes two arguments: the accumulator and the currentValue. The initialValue is set to 0. The callback function adds the accumulator and the currentValue and stores the result in the accumulator. The callback function is called for each element in the numbers array, starting with the first element and the initialValue of 0. The final result of the reduce() method is the sum of all the elements in the numbers array.

You can also use the reduce() method to sum an array of numbers with a non-zero initialValue:

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

const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 10);

console.log(sum); // Output: 20

In this example, the initialValue is set to 10, so the sum starts at 10 rather than 0. The final result of the reduce() method is the sum of all the elements in the numbers array, plus the initialValue of 10.

You can also use the reduce() method to sum an array of numbers with a different callback function:

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

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

console.log(sum); // Output: 10

In this example, the callback function is an arrow function that returns the sum of the accumulator and the currentValue. The initialValue is still set to 0. The final result of the reduce() method is the sum of all the elements in the numbers array.

Example of reducing an array of objects with the JavaScript reduce method

To use the reduce() method to reduce an array of objects, you can pass a callback function that takes two arguments: the accumulator and the currentValue, and returns a new object that combines the properties of the accumulator and currentValue objects.

Here is an example of using the reduce() method to reduce an array of objects:

const people = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
  { name: 'Charlie', age: 35 }
];

const summary = people.reduce((accumulator, currentValue) => {
  return {
    totalAge: accumulator.totalAge + currentValue.age,
    count: accumulator.count + 1
  };
}, { totalAge: 0, count: 0 });

console.log(summary); // Output: { totalAge: 90, count: 3 }

In this example, the callback function takes two arguments: the accumulator and the currentValue. The initialValue is set to an object with totalAge and count properties set to 0. The callback function creates a new object that combines the properties of the accumulator and currentValue objects. The callback function is called for each element in the people array, starting with the first element and the initialValue object. The final result of the reduce() method is an object with the total age of all the people in the people array and the count of people in the people array.

You can also use the reduce() method to reduce an array of objects with a different callback function:

const people = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
  { name: 'Charlie', age: 35 }
];

const summary = people.reduce((accumulator, currentValue) => {
  accumulator.totalAge += currentValue.age;
  accumulator.count++;
  return accumulator;
}, { totalAge: 0, count: 0 });

console.log(summary); // Output: { totalAge: 90, count: 3 }

In this example, the callback function is a function that updates the totalAge and count properties of the accumulator object and returns the accumulator object. The initialValue is still set to an object with totalAge and count properties set to 0. The final result of the reduce() method is the same as in the previous example: an object with the total age of all the people in the people array and the count of people in the people array.

Reducing an object with the JavaScript reduce method

To use the reduce() method to reduce an object, you can first convert the object to an array of key-value pairs using the Object.entries() method, and then use the reduce() method to process the array of key-value pairs.

Here is an example of using the reduce() method to reduce an object:

const obj = { a: 1, b: 2, c: 3 };

const sum = Object.entries(obj).reduce((accumulator, [key, value]) => accumulator + value, 0);

console.log(sum); // Output: 6

In this example, the Object.entries() method is used to convert the obj object to an array of key-value pairs. The reduce() method is then called on the array of key-value pairs, and a callback function that takes two arguments: the accumulator and the currentValue (which is an array with the key and value of the current key-value pair). The callback function adds the currentValue (which is the value of the current key-value pair) to the accumulator and returns the result. The initialValue is set to 0. The callback function is called for each key-value pair in the obj object, starting with the first key-value pair and the initialValue of 0. The final result of the reduce() method is the sum of all the values in the obj object.

You can also use the reduce() method to reduce an object with a different callback function:

const obj = { a: 1, b: 2, c: 3 };

const sum = Object.entries(obj).reduce((accumulator, [key, value]) => {
  accumulator[key] = value;
  return accumulator;
}, {});

console.log(sum); // Output: { a: 1, b: 2, c: 3 }

In this example, the callback function is a function that adds the key-value pair from the currentValue array to the accumulator object and returns the accumulator object. The initialValue is set to an empty object. The callback function is called for each key-value pair in the obj object, starting with the first key-value pair and the initialValue of an empty object. The final result of the reduce() method is an object with the same key-value pairs as the original obj object.

Using the JavaScript reduce method to sum an array of objects

To use the reduce() method to sum the values of a specific property in an array of objects, you can pass a callback function that takes two arguments: the accumulator and the currentValue, and returns the sum of the values of the specific property in the accumulator and currentValue objects.

Here is an example of using the reduce() method to sum the values of a specific property in an array of objects:

const objects = [
  { id: 1, value: 10 },
  { id: 2, value: 20 },
  { id: 3, value: 30 }
];

const sum = objects.reduce((accumulator, currentValue) => accumulator + currentValue.value, 0);

console.log(sum); // Output: 60

In this example, the callback function takes two arguments: the accumulator and the currentValue. The initialValue is set to 0. The callback function adds the value property of the currentValue object to the accumulator and returns the result. The callback function is called for each element in the objects array, starting with the first element and the initialValue of 0. The final result of the reduce() method is the sum of the values of the value property of all the objects in the objects array.

You can also use the reduce() method to sum the values of a specific property in an array of objects with a different callback function:

const objects = [
  { id: 1, value: 10 },
  { id: 2, value: 20 },
  { id: 3, value: 30 }
];

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

console.log(sum); // Output: 60

In this example, the callback function is a function that returns the sum of the accumulator and the value property of the currentValue object. The initialValue is still set to 0. The final result of the reduce() method is the same as in the previous example: the sum of the values of the value property of all the objects in the objects array.

Reducing an array of objects by a specific key with the JavaScript reduce method

You can use the reduce() method to reduce an array of objects by a specific key by using the callback function to iterate through the array, and using the key to access the value of each object.

Here’s an example of using the reduce() method to sum the values of the price key for a list of objects representing products:

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

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

console.log(totalPrice); // Output: 45

In this example, the callback function is used to iterate through the products array and add the price of each object to the accumulator. The initial value of the accumulator is set to 0, so the first time the callback function is called, the accumulator is 0 and the current value is the first object in the array. The callback function then adds the price of the first object (10) to the accumulator and returns the result (10). On the next iteration, the accumulator is now 10 and the current value is the second object in the array. The callback function adds the price of the second object (15) to the accumulator (10) and returns the result (25). This process continues until all elements in the array have been processed, and the final value of the accumulator is returned.

You can use the reduce() method similarly to reduce an array of objects by any key. Update the callback function to access the key value you want to reduce by, and update the initial value as needed.

Asynchronously reducing an array with the JavaScript reduce method

If you want to use the reduce() method to asynchronously process an array, you can use the async/await syntax to make the reduce() method return a promise that resolves to the final reduced value.

Here’s an example of using the reduce() method with async/await to asynchronously process an array of numbers:

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

const sum = await numbers.reduce(async (acc, cur) => {
  // Wait for the accumulator to resolve to a value
  acc = await acc;
  // Return the sum of the accumulator and the current value
  return acc + cur;
}, 0);

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

In this example, the reduce() method is called with an asynchronous callback function that uses await to wait for the accumulator to resolve to a value before returning the sum of the accumulator and the current value. The initial value of the accumulator is set to 0, so the first time the callback function is called, the accumulator is 0 and the current value is the first element in the array (1). The callback function then returns the sum of the accumulator (0) and the current value (1), which is 1. On the next iteration, the accumulator is now 1 and the current value is the second element in the array (2). The callback function then returns the sum of the accumulator (1) and the current value (2), which is 3. This process continues until all elements in the array have been processed, and the final value of the accumulator is returned.

You can use the reduce() method with async/await in a similar way to asynchronously process an array of objects. Simply update the callback function to perform asynchronous operations on each object, and update the initial value as needed.

Sharing is caring 🙂