reduce()

PHOTO EMBED

Sun May 22 2022 21:41:26 GMT+0000 (Coordinated Universal Time)

Saved by @Luduwanda #javascriptreact

//!Trickiest of all array methods

const arr = [1,2,3,4,5]
//undefined

//Array method for two goals:
//1. end up with one value in the end
//2. persist the return or the outcome of iterating over our elements in each subsequent iteration

//reduce() takes two arguments

//So in the first run, accumulator = 0
//Second argument ("0") means we start with the value 0

arr.reduce((accumulator, currentElement) =>
accumulator + currentElement, 0)
//15 

//How this function works:
//first run: accu = 0 + cV 1 

//second run: accu = 1 + cv 2

//third run: accu = 3 + cv 3

//fourth run: accu = 6 + cv 4

//fifth run: accu = 10 + cv 5 

// --> 15 (end result)


//if we choose as second argument 10 instead of 0
//then the accumulator starts at 10
content_copyCOPY