-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patharr_reduce.js
29 lines (22 loc) · 996 Bytes
/
arr_reduce.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/*
CONDENSE ARRAYS WITH REDUCE
The array method reduce is used to iterate through an array and condense it into
one value.
To use reduce you pass in a callback whose arguments are an accumulator (in this
case, previousVal) and the current value (currentVal).
reduce has an optional second argument which can be used to set the initial value of
the accumulator. If no initial value is specified it will be the first array element
and currentVal will start with the second array element.
Here is an example of reduce being used to subtract all the values of an array:
var singleVal = array.reduce(function(previousVal, currentVal) {
return previousVal - currentVal;
}, 0);
Use the reduce method to sum all the values in array and assign it to singleVal.
*/
var array = [4,5,6,7,8];
var singleVal = 0;
// Only change code below this line.
singleVal = array.reduce(function(a, b) { //'a' = previousVal; 'b' = currentVal
return a + b;
}, 0);
console.log("Print singleVal: ", singleVal);