Tuesday, February 14, 2023

JavaScript Array reduce() Method With Examples

The JavaScript Array reduce() method executes a reducer function (a callback function) on each element of the array and returns a single value (reduces the array elements to a single value).

Syntax of reduce method

reduce(callbackFunction, initialValue)

// Callback function definition
function callbackFunction(accumulator, currentValue) {
  return FINAL_VALUE;
}

If written as arrow function

reduce((accumulator, currentValue) => { /* … */ }, initialValue)

Parameters

  1. callbackFunction- A function to execute for each element in the array. The return value in each call to callback function becomes the value of the accumulator parameter on the next invocation of callback function.

    The callback function is called with the following arguments:

    • accumulator- Accumulates the callback function's return values. At any time it stores the value resulting from the previous call to callback function.
    • currentValue- The value of the current element passed from the array.
  2. initialValue- It is an optional parameter. If passed then accumulator is initialized to the initialValue the first time callback function is called. Then callback function starts executing with the first value in the array as currentValue.
    If initialValue is not specified, accumulator is initialized to the first value in the array, and callback function starts executing with the second value in the array as currentValue.

Reduce method JavaScript example

1. Using reduce to sum all elements in an array.

const numArr = [4, 5, 6, 7, 8, 9];
const sum = numArr.reduce((accumulator, element) => accumulator + element);
console.log(sum); // 39

Same example when written with an explicit callback function.

const numArr = [4, 5, 6, 7, 8, 9];
const sum = numArr.reduce(sumFun);
console.log(sum);//39
//callback function
function sumFun(accumulator, element) {
  return accumulator + element
}

Let's try to understand how does reducer function work with the above example. As you know accumulator stores the return value of the function.

When the function is run for the first time there is no return value of the previous calculation. So, in first iteration, if initialValue is passed then that is stored in the accumulator otherwise the array element at index 0 is stored.

In our example there is no initialValue, so accumulator has numArr[0] which means 4 and currentValue is numArr[1] which means 5, in the first iteration. Return value is 9.

In the second iteration accumulator has the return value of the previous iteration which means 9 and currentValue is numArr[2] which means 6. Return value is 15.

Same procedure is followed in other iterations.

2. Using reduce to sum all elements in an array, when an initial value is also passed.

const numArr = [4, 5, 6, 7, 8, 9];
const sum = numArr.reduce((accumulator, element) => accumulator + element, 10);
console.log(sum);  // 49

Since there is an initial value now, so that is stored in the accumulator in the first iteration and currentValue stored numArr[0].

3. Counting occurrence of each element in an array and storing them in an object.

const numArr = [100, 2, 4, 100, 6, 1, 4, 1, 6];
const elementCount = numArr.reduce((numCount, num) => {
  let count = numCount[num] > 0 ? numCount[num] : 0;
  numCount[num] = ++count;
  return numCount;
}, {});
console.log(elementCount); // {1: 2, 2: 1, 4: 2, 6: 2, 100: 2}

4. Group objects by one of the object properties. In this example we have an array of Person objects which will be grouped on gender property. Note that spread operator is used to expand the array.

const persons = [{id:1, name:"Ajay", gender:"M"}, 
   {id:2, name:"Rajiv", gender:"M"}, 
   {id:3, name:"Bethany", gender:"F"},
   {id:4, name:"Albert", gender:"M"}, 
   {id:5, name:"Amy", gender:"F"},];
   
function groupObjectsByProperty(array, property){
  return array.reduce((accumulator, personObj) => {
    let groupingKey = personObj[property];
    let grp = !accumulator[groupingKey] ? [] : accumulator[groupingKey];
    return { ...accumulator, [groupingKey]: [...grp, personObj] };
  }, {});
}

// Function call
const groupedPeople = groupObjectsByProperty(persons, "gender");
console.log(groupedPeople);

Output

{
 F: [
	{id: 3, name: 'Bethany', gender: 'F'}.
	{id: 5, name: 'Amy', gender: 'F'}
 ],
  M: [
	{id: 1, name: 'Ajay', gender: 'M'},
	{id: 2, name: 'Rajiv', gender: 'M'},
	{id: 4, name: 'Albert', gender: 'M'}
 ]
}

That's all for this topic JavaScript Array reduce() Method With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. JavaScript Array map() Method With Examples
  2. JavaScript Array slice() method With Examples
  3. JavaScript Arrow Function With Examples
  4. React HelloWorld App - First React App
  5. React create-react-app Project Structure

You may also like-

  1. Unmodifiable or Immutable List in Java
  2. Reverse Each Word in a String Java Program
  3. this Keyword in Java With Examples
  4. Constructor in Python - __init__() function
  5. BeanPostProcessor in Spring Framework

No comments:

Post a Comment