JavaScript: use of Reduce() or ReduceRight() methods

JavaScript

In this article, we are going to learn about reduce() and reduceright() functions in JavaScript. array.Reduce() is a standard built function of the array. It runs a reducer or callback function on each element of the array and returns a single value output.(from left-to-right)

Why should we use reduce() over For loop in JavaScript

  • Reduce() help us to get rid of for loop to perform any operation on the array. It makes our code less and achieves more.
  • Reducer or callback makes us perform multiple operations on the array at once.
  • Reduce() function support functional programming.
  • It makes our work so easy to automatically set up the iteration variable in the function.

Let us understand with example:

For Loop to sum the elements of array

let array = [6, 7, 10,3];

let num=1;
for (let i = 0; i < array.length; i++) {
    num= num*array[i];
}
console.log(num);

Output:

1260

array.reduce() function to sum the elements of array

In this code example we are we are calculating the sum of all array element and printing on console.

let array = [6, 7, 10,3];
const reducer = (accumulator, currentValue) => accumulator * currentValue;
console.log(array.reduce(reducer));

Output:

1260

array.Reduce() step by step explanation

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

Reducer or callback

//This is Callback or reducer
callback( accumulator, currentValue, [, index[, array]] )

Reduce() method call the reducer (callback( accumulator, currentValue, [, index[, array]] )) a callback function for each element of array.Which takes the four arguments.

Parameters of Reduce() function

  1. Callback function: We also call it reducer, it calls each element of the array.

The callback function has four arguments.

  • accumulator(acc): It is the return value from the previous result innovation or Initial value if it is supplied.
  • currentValue(optional):The current value of array element
  • index(optional): It contain current element index,If initalValue is pass then it starts from index 0 else index 1.
  • array(optional): array for which we are executing reducer.

2. initalValue(optional): The initial accumulator value that uses when the first time the callback function is called. If initalValue is not given then the first element of the array is used as an accumulator.

Notes:

If we call reduce() on an empty array without initalValue we will get Typerror(is thrown when the operation could not be performed on the object).

Different examples using the Array’s reduce() function

Sum elements of object Array using reduce()

Here, in this example we are calculating sum of array object’s element using reduce() array method.

let initialValue = 0
let sum_arryobject = [{a: 6}, {a: 7}, {a: 8},{a:9}].reduce(function (accu, currValue) {
    return accu + currValue.a
}, initialValue)

console.log('Sum='+sum_arryobject)

Output:

sum = 30

Remove duplicate from array using reduce()

In this code example we are removing the duplicate array’s elements using reduce() method.

let dup_array = [12, 15, 12, 11, 10, 11, 15]
let uniquearray = dup_array.reduce(function (accum, currentValue) {
  if (accum.indexOf(currentValue) === -1) {
    accum.push(currentValue)
  }
  return accum
}, [])

console.log(uniquearray)

Output:

[12, 15, 11, 10]

Nested Array to Object Using java script reduce()

In this code example we are converting a nested array into object.

let myarray = [['Name','Jonson'],['Age',20],['Desigi','MGR'],['Comp','UNS']]

let ArrayToObject = (myarray, key) =>
  array.reduce(
    (obj, element) => ({
      ...obj,
      [element[key]]: element
    }),
    {}
  );
const return_obj = Object.fromEntries(myarray)
console.log(return_obj)

Output:

{
  Age: 20,
  Comp: "UNS",
  Desigi: "MGR",
  Name: "Jonson"
}

Flatten an array using Reduce() in javascript

In this code example we are converting the array of array into 1 dimensional array.We can achieve easily using reduce() method.

let arraytflatten = [[10, 11], [20, 34], [46, 50],[3,4]].reduce(
  ( accum, currVal ) => accum.concat(currVal),
  []
)
console.log(arraytflatten)

Output:

[10, 11, 20, 34, 46, 50, 3, 4]

Using of reduceRight() in javascript

reduceRight() is a stand built-in function of the array, it uses a callback function on each value of the array( from right-to-left) and return a single value as output.

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

Callback function in reducerRight()

array.reduceRight(function(accumulator, currentValue, index, array) {  // ...});

Let Understand with an example

Flatten an array using reducerRight()

var arraytoflat = [[7, 1], [6, 1], [10, 5]].reduceRight(function(accum,currval ) {
    return accum.concat(currval);
}, []);
console.log(arraytoflat)

Output:

[10, 5, 6, 1, 7, 1]

Here we can see reducerRight() concate from right to left.[10,5] is the last array in arraytoflat.