;

Javascript Array - reduce() Method


Tutorialsrack 29/10/2022 Jquery Javascript

In this article, you will learn about the javascript Array built-in method Array.prototype.reduce(). How does this method work in javascript? 

Array.prototype.reduce()

The Array.prototype.reduce() method executes a user-supplied "reducer" callback function on each element of the array, from left to right and it returns a single value.

Syntax
array.reduce(callback(previousValue ,currentValue, currentIndex, array) ,initialValue);

This method takes 2 parameters as given below:

  • callback: This parameter holds the function to be called for each element of the array. Each time the callback function executes, the returned value is added to the newArray. This function takes the mentioned parameters below:
    • previousValue: This parameter holds the result from the previous call to callbackFn. On the first call, if initialValue is specified, otherwise the value of  previousValue is array[0].
    • currentValue: This parameter holds the index of the current element within the array. On the first call, the value of array[0] if an initialValue was specified, otherwise the value of array[1].
    • currentIndex: This parameter holds the index position of currentValue in the array. On the first call, if initialValue was specified then it will be 0, otherwise 1.
    • array(Optional): This parameter holds the reference to the original array.
  • initialValue(Optional): This parameter holds the value that will be passed to callback function on the first call. If initialValue is not provided, the first element acts as the initialValue on the first call, and callback function won't execute on it.

The reduce() does not change the original array. And it executes a callback function once for each array element in order.

Here are some examples of Array.prototype.reduce() method:

Example 1: Using reduce()  Method Without Initial Value

Example
/*
In this example, you can see how to reduce() method behaves
without passing initialValue
*/
const arr = [40, 90, 160, 250, 360];

function reducer(previousValue, currentValue, index) {
  const returns = previousValue + currentValue;
  console.log(
    `previousValue: ${previousValue}, currentValue: ${currentValue}, index: ${index}, returns: ${returns}`,
  );
  return returns;
}

arr.reduce(reducer);


/*
The callback would be invoked four times, 
with the arguments and return values in each call being as follows:
--------------------------Output---------------------------------


"previousValue: 40, currentValue: 90, index: 1, returns: 130"
"previousValue: 130, currentValue: 160, index: 2, returns: 290"
"previousValue: 290, currentValue: 250, index: 3, returns: 540"
"previousValue: 540, currentValue: 360, index: 4, returns: 900"


*/

In the above example, The array parameter never changes through the process - it's always  [40, 90, 160, 250, 360]

The value returned by reduce() method would be that of the last callback invocation (900).

Example 2: Using reduce() Method With Initial Value

Example 
/*
In this example, you can see how reduce() method behaves
when we passing initialValue
*/
const arr = [40, 90, 160, 250, 360];

function reducer(previousValue, currentValue, index) {
  const returns = previousValue + currentValue;
  console.log(
    `previousValue: ${previousValue}, currentValue: ${currentValue}, index: ${index}, returns: ${returns}`,
  );
  return returns;
}

arr.reduce(reducer, 100);


/*
The callback would be invoked five times, 
with the arguments and return values in each call being as follows:
--------------------------Output---------------------------------


"previousValue: 100, currentValue: 40, index: 0, returns: 140"
"previousValue: 140, currentValue: 90, index: 1, returns: 230"
"previousValue: 230, currentValue: 160, index: 2, returns: 390"
"previousValue: 390, currentValue: 250, index: 3, returns: 640"
"previousValue: 640, currentValue: 360, index: 4, returns: 1000"


*/

The value returned by reduce() method would be that of the last callback invocation (1000).

Example 3: Flatten an Array Using reduce Method

Example
const arr = [40, 90, 160, 250, 360, [720, 1440], 2880];

// Flattening an array using reduce() method
console.log(arr.reduce((previousValue, currentValue) => previousValue.concat(currentValue),
  []));
// Output => [40, 90, 160, 250, 360, 720, 1440, 2880]

Example 4: Remove Duplicate Items in an Array

Example
const arr = [40, 90, 360, 40,160, 250, 360, 720, 1440, 2880, 250];


// Removing a duplicate elements from an array using reduce() method
const newArrayWithNoDuplicates = arr.reduce(
  (previousValue, currentValue) => {
    if (!previousValue.includes(currentValue)) {
      return [...previousValue, currentValue];
    }
    return previousValue;
  },
  [],
);

console.log(newArrayWithNoDuplicates)
// Output => [40, 90, 360, 160, 250, 720, 1440, 2880]

Example 5: Grouping Objects by Property Using a reduce() Method

Example
let actor = [
  { name: "Tom Holland", age: 21 },
  { name: "Cillian Murphy", age: 45 },
  { name: "Tom Hardy", age: 40 },
  { name: "Ben Affleck", age: 45 },
  { name: "Oscar", age: 21 },
  { name: "Gal Gadot", age: 37 },
];

function groupBy(objectArray, property) {
  return objectArray.reduce(function (previousValue, currentValue) {
    let key = currentValue[property];
    if (!previousValue[key]) {
      previousValue[key] = [];
    }
    previousValue[key].push(currentValue);
    return previousValue;
  }, {});
}

let groupedPeople = groupBy(actor, "age");
console.log(groupedPeople);

/*
---------------------Output---------------------

{
    21: [
        {
            "age": 21,
            "name": "Tom Holland"
        },
        {
            "age": 21,
            "name": "Oscar"
        }
    ],
    37: [
        {
            "age": 37,
            "name": "Gal Gadot"
        }
    ],
    40: [
        {
            "age": 40,
            "name": "Tom Hardy"
        }
    ],
    45: [
        {
            "age": 45,
            "name": "Cillian Murphy"
        },
        {
            "age": 45,
            "name": "Ben Affleck"
        }
    ]
}


*/

Example 6: Using reduce() with sparse arrays

The reduce() method skips missing elements in sparse arrays, but it does not skip undefined values in an array.

Example
//reduce() skips the missing element from an array and return a single value
console.log([1, 2, , 4, 5, 6, null].reduce((a, b) => a + b));
// Output => 18

//reduce() does not skip the undefined element from an array 
//and return a NaN
console.log([1, 2, undefined, 4, 5, 6].reduce((a, b) => a + b));
// Output => NaN

I hope this article will help you to understand the javascript Array built-in method Array.prototype.reduce()

Share your valuable feedback, please post your comment at the bottom of this article. Thank you!


Related Posts



Comments

Recent Posts
Tags