Skip to content

Commit 1f86c82

Browse files
committed
complete reduce method
1 parent a291658 commit 1f86c82

File tree

1 file changed

+60
-4
lines changed

1 file changed

+60
-4
lines changed

11_Working_with_Arrays/script.js

Lines changed: 60 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ const account4 = {
3333
pin: 4444,
3434
};
3535

36+
const movements = [200, 450, -400, 3000, -650, -130, 70, 1300];
3637
const accounts = [account1, account2, account3, account4];
3738

3839
// Elements
@@ -81,9 +82,16 @@ const displayMovements = function (movements) {
8182
};
8283
displayMovements(account1.movements);
8384

85+
const calcDisplayBalance = function (movements) {
86+
const balance = movements.reduce((acc, mov) => acc + mov, 0);
87+
labelBalance.textContent = `${balance}£`;
88+
};
89+
90+
calcDisplayBalance(account1.movements);
91+
8492
const createUsernames = function (acc) {
85-
acc.forEach(function (acc) {
86-
acc.username = acc.owner
93+
acc.forEach(function (name) {
94+
name.username = name.owner
8795
.toLowerCase()
8896
.split(' ')
8997
.map(letter => letter[0])
@@ -103,8 +111,6 @@ const currencies = new Map([
103111
['GBP', 'Pound sterling'],
104112
]);
105113

106-
const movements = [200, 450, -400, 3000, -650, -130, 70, 1300];
107-
108114
const euroToUsd = 1.1;
109115
// const movementsUSD = movements.map(function (mov) {
110116
// return mov * euroToUsd;
@@ -127,6 +133,56 @@ const movementsDescriptions = movements.map(
127133
);
128134
console.log(movementsDescriptions);
129135

136+
console.log('🔸Filter Method🔸');
137+
const deposits = movements.filter(function (mov, i, arr) {
138+
return mov > 0;
139+
});
140+
141+
console.log(deposits);
142+
143+
console.log('🔸For of loop🔸');
144+
const depositsFor = [];
145+
for (const mov of movements) {
146+
if (mov > 0) {
147+
depositsFor.push(mov);
148+
}
149+
}
150+
151+
console.log(depositsFor);
152+
153+
const withdrawals = movements.filter(mov => mov < 0);
154+
console.log(withdrawals);
155+
156+
console.log(movements);
157+
158+
// accumulator => Snowball that keeps adding up.
159+
console.log('🔸Reduce Method🔸');
160+
// const balance = movements.reduce(function (accumulator, currentEl, index, arr) {
161+
// console.log(`Iteration ${index}: ${accumulator}`);
162+
// return accumulator + currentEl;
163+
// }, 0);
164+
const balance = movements.reduce(
165+
(accumulator, currentEl, index, arr) => accumulator + currentEl,
166+
0
167+
);
168+
console.log(balance);
169+
170+
console.log('🔸For of loop🔸');
171+
let balance2 = 0;
172+
for (const mov of movements) balance2 += mov;
173+
console.log(balance2);
174+
175+
// Maximum value
176+
const max = movements.reduce((acc, mov) => {
177+
if (acc > mov) {
178+
return acc;
179+
} else {
180+
return mov;
181+
}
182+
}, movements[0]);
183+
184+
console.log(max);
185+
130186
/////////////////////////////////////////////////
131187

132188
// // SLICE

0 commit comments

Comments
 (0)