0
Can anyone plz explain me this
let arr = [1,2,3,4,5]; const avg = arr.reduce((acc,curEle,index,arr) =>{ let total = acc + curEle; if(index == arr.length-1){ return total /arr.length; } return total; }); console.log(avg);
4 odpowiedzi
+ 2
Reduce will loop trought array and run custom function.
This function have 4 arguments. 2 required, previous returned value, current element of array. 2 optional: index of current element and array itself
This function will calculate total sum of each elements of array, by adding current element(curEle) to previous(acc)
When index is last it will return average number of all numbers from array by dividing total with length
+ 2
One is return what will become acc, previous value. (Return total)
Inside if is return when loop is ended, this is value of avg, what is printed with console.log(avg), try removing if and you will see that console will show sum of all numbers from array.
Because we need to return (total) to have previous value for reduce to work, but inside code we search for average,and we need this data. At last iteration first return inside if will break from reduce function and set that value to avg
Your reduce dont need to have more return, but this one have only because we need 2 diferent data, every return will become previousValue(acc)
0
Why there are 2 returns ?