How to use reduce() method to execute a reducer function on each element of the array in JavaScript

3 Answers

0 votes
const arr = [11, 22, 33, 44, 55];
 
arr.reduce((accumulator, currentValue, currentIndex, array) => {
    console.log("accumulator:" + accumulator);
    console.log("currentValue:" + currentValue);
    console.log("currentIndex:" + currentIndex + "\n");
  
    return accumulator + currentValue
}, 1)
  
 
  
     
/*
run:
           
"accumulator:1"
"currentValue:11"
"currentIndex:0

"accumulator:12"
"currentValue:22"
"currentIndex:1

"accumulator:34"
"currentValue:33"
"currentIndex:2

"accumulator:67"
"currentValue:44"
"currentIndex:3

"accumulator:111"
"currentValue:55"
"currentIndex:4
"
         
*/

 



answered Nov 6, 2019 by avibootz
edited Oct 17, 2022 by avibootz
0 votes
const arr = [1, 2, 3, 4, 5];
 
const reducer = (accumulator, currentValue) => accumulator + currentValue;
 
// 1 + 2 + 3 + 4 + 5
console.log(arr.reduce(reducer));
  
 
  
     
/*
run:
           
15 
         
*/

 



answered Nov 6, 2019 by avibootz
edited Oct 17, 2022 by avibootz
0 votes
const arr = [1, 2, 3, 4, 5];
 
const reducer = (accumulator, currentValue) => accumulator + currentValue;
 
// 1 + 2 + 3 + 4 + 5 + 6
console.log(arr.reduce(reducer, 6));
  
 
  
     
/*
run:
           
21
         
*/

 

 



answered Nov 6, 2019 by avibootz
edited Oct 17, 2022 by avibootz
...