Reducing Arrays to a Single Value By Using the reduce() Method in JavaScript


The reduce() method in JavaScript is a powerful array method that allows you to iterate through an array and reduce it to a single value. This method can be used for a variety of tasks such as summing the values of an array, flattening an array, or counting the occurrences of an element.

The syntax for the reduce() method in JavaScript is as follows:

array.reduce(function(accumulator, currentValue, currentIndex, array) {
  // code to be executed on each iteration
}, initialValue);
  • array : is the array on which the reduce() method is being called.
  • function(accumulator, currentValue, currentIndex, array) : is the callback function that is executed on each iteration. It takes four arguments:
  • accumulator : is the accumulated value that is returned on each iteration. It starts with the initialValue (if provided) or the first element of the array (if no initialValue is provided)
  • currentValue : is the current element of the array that is being processed.
  • currentIndex : is the index of the current element of the array that is being processed.
  • array : is the array on which the reduce() method is being called.
  • initialValue(optional) : is the starting value for the accumulator. If no initialValue is provided, the first element of the array is used as the starting value.

The reduce() method returns a single value that is the result of executing the callback function on each element of the array.

Example 1: Summing the values of an array

let numbers = [1, 2, 3, 4, 5];
let sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue);
console.log(sum); // 15

In this example, we use the reduce() method to sum the values of an array of numbers. The accumulator starts at the first element of the array and the currentValue is the next element. We use the accumulator to store the sum and add the currentValue to it on each iteration.

Example 2: Flattening an array

let nestedArray = [[1, 2], [3, 4], [5, 6]];
let flattenedArray = nestedArray.reduce((accumulator, currentValue) =>accumulator.concat(currentValue));
console.log(flattenedArray); // [1, 2, 3, 4, 5, 6]

In this example, we use the reduce() method to flatten an array of arrays. We use the concat() method to merge the currentValue (which is an array) into the accumulator which is also an array).

Example 3: Counting the occurrences of an element

let colors = ['red', 'blue', 'green', 'red', 'blue', 'yellow'];
let colorCounts = colors.reduce((accumulator, currentValue) => {
  if (currentValue in accumulator) {
    accumulator[currentValue]++;
  } else {
    accumulator[currentValue] = 1;
  }
  return accumulator;
}, {});
console.log(colorCounts); // { red: 2, blue: 2, green: 1, yellow: 1 }

In this example, we use the reduce() method to count the occurrences of each element in an array. We use an object as the accumulator and check if the currentValue already exists in the object. If it does, we increment the value by 1. If it doesn't, we add the currentValue as a key to the object and set its value to 1.

Example 4: Finding the largest value in an array

let numbers = [5, 10, 15, 20, 25];
let largest = numbers.reduce((accumulator, currentValue) => {
  return Math.max(accumulator, currentValue);
});
console.log(largest); // 25

In this example, we use the reduce() method to find the largest value in an array of numbers. We use the Math.max() method to compare the accumulator and the currentValue on each iteration and return the larger value. The final value returned by the reduce() method is the largest value in the array.

Example 5: Grouping elements by a certain property

let people = [
{ name: 'Rakesh', age: 25, city: 'Chennai' },
{ name: 'Raj', age: 30, city: 'Salem' },
{ name: 'Sara', age: 35, city: 'Chennai' }
];

let groupedByCity = people.reduce((accumulator, currentValue) => {
  if (currentValue.city in accumulator) {
accumulator[currentValue.city].push(currentValue);
  } else {
accumulator[currentValue.city] = [currentValue];
  }
  return accumulator;
}, {});

console.log(groupedByCity); 
/* 
{ 
Chennai: [{ name: 'Rakesh', age: 25, city: 'Chennai' }, { name: 'Sara', age: 35, city: 'Chennai' }], 
Salem: [{ name: 'Raj', age: 30, city: 'Salem' }] 
}
*/
Conclusion

The reduce() method in JavaScript is a powerful tool for working with arrays. It allows for the iteration and calculation of values within an array, making it easy to perform tasks such as summing or finding the product of all elements in an array. The reduce() method takes a callback function as an argument, which is used to specify the calculation to be performed on each element of the array. The callback function takes two arguments: an accumulator and the current value. The accumulator is used to store the result of the calculation as the function iterates through the array. The initial value for the accumulator can be provided or it takes the first element of the array as the starting value. Overall, the reduce() method is a useful and versatile tool for working with arrays in JavaScript.

List of Programs


JS Practical Questions & Answers


JS Practical Project