Complete guide to Javasript .reduce() function

Javascript reduce() method reduces the array to a single value. It can also executes a provided function for each value of the array (from left-to-right). The return value of the function is stored in an accumulator (result/total).

Syntax of .reduce() function

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

Parameters

  • total Required – The initialValue, or the previously returned value of the function
  • currentValue Required – The value of the current element
  • currentIndex Optional. – The array index of the current element
  • arr Optional – The array object the current element belongs to

Sum up a Javascript array using .reduce() function


const numbers=[1,2,3,4,5];
const sum = numbers.reduce((total,currentValue)=>{
return total+currentValue;
});
// another shorter version of the syntax
//const sum = numbers.reduce((total,currentValue)=>total+currentValue);
console.log('Sumf of numbers: ', sum); // output: Sumf of numbers: 15

Average of numbers using Javascript .reduce() function

const numbers=[1,2,3,4,5];
const average = numbers.reduce((total,currentValue,index,array)=>{
total+=currentValue;
if(index===array.length-1){
return total/array.length
}else
return total;
});
console.log('Average of numbers: ',average);
//output: Average of numbers: 3

Initial Value of total parameter

Se can set an initial value of total. In this current example we will doubled the numbers array into a second array. To do this we have to initialize an empty array for total just after the end of curly braces.

const numbers=[1,2,3,4,5];
const doubled = numbers.reduce((total,currentValue)=>{
total.push(2*currentValue);
return total;
},[]);
console.log('Doubled numbers: ',doubled);

Create tally or count array elements using .reduce() function

To create tally or count element we have to initialise our tally(previously total) value into an object ({}) not an array.

const fruits = ['banana', 'cherry', 'orange', 'apple', 'cherry', 'orange', 'apple', 'banana', 'cherry', 'orange', 'fig' ];
const count = fruits.reduce((tally,fruit)=>{
tally[fruit] = (tally[fruit]) ? tally[fruit]+1 : 1;
return tally;
},{});
console.log(count);
//output: {banana:2, cherry:3, orange:3, apple:2, fig:1}

Combining arrays or concating arrays using .reduce() function


const numbers = [[1,2,3], [4,5,6], [7,8,9]];
const newNumbers = numbers.reduce((total,currentValue)=>{
return total.concat(currentValue);
},[]);

console.log(newNumbers);
//output: [1,2,3,4,5,6,7,8,9]