Skip to content

Commit cbb5f55

Browse files
committed
Learned about reduce
1 parent bb47fc6 commit cbb5f55

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

05_Iterations/eight_reduce.js

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
// Reduce
2+
3+
const myNums = [1, 2, 3]
4+
5+
const total = myNums.reduce( function (acc, currval) {
6+
console.log(`acc: ${acc} and currVal: ${currval}`);
7+
return acc + currval
8+
}, 0 /* acc start value */ )
9+
console.log(total);
10+
11+
/* Output:
12+
acc: 0 and currval: 1 (0 + 1)
13+
acc: 1 and currval: 2 (1 + 2)
14+
acc: 3 and currval: 3 (3 + 3)
15+
6 (total)
16+
17+
--------------------------------------------------------------------
18+
'Reduce' in Arrow function */
19+
20+
const myTotal = myNums.reduce( (acc, curr) => acc + curr, 0 )
21+
22+
console.log(myTotal); /* Output: 6
23+
24+
--------------------------------------------------------------------
25+
Real life example */
26+
27+
const shopppingCart = [
28+
{
29+
itemName: "JS Course",
30+
price: 2999
31+
},
32+
{
33+
itemName: "Py Course",
34+
price: 999
35+
},
36+
{
37+
itemName: "Mobile dev Course",
38+
price: 5999
39+
},
40+
{
41+
itemName: "Data Science Course",
42+
price: 12999
43+
},
44+
]
45+
46+
const priceToPay = shopppingCart.reduce( (acc, item) => acc + item.price, 0 )
47+
console.log(priceToPay); // Output: 22996

0 commit comments

Comments
 (0)