I found a very useful function reduce(), and I\'m using it, but I\'m not sure if I understand it properly. Can anyone help me to understand this function?
reduce() method has two parameters: a callback function that is called for every element in the array and an initial value.
The callback function also has two parameters: an accumulator value and the current value.
The flow for your array ([1, 2, 3, 4, 5, 6]) is like this:
1. return 0 + 1 // 0 is the accumulator which the first time takes the initial value, 1 is the current value. The result of this becomes the accumulator for the next call, and so on..
2. return 1 + 2 // 1 - accumulator, 2 - current value
3. return 3 + 3 // 3 - accumulator, 3 - current value, etc...
4. return 6 + 4
5. return 10 + 5
6. return 15 + 6
And when reached to the end of the array, return the accumulator, which here is 21