Last active
June 29, 2023 01:36
-
-
Save kironroy/9c5609461d0824f2637898356951ffe7 to your computer and use it in GitHub Desktop.
map and multi-dim arrays
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Data | |
const account1 = { | |
owner: 'Bobby Khan', | |
movements: [2030, 450, -400, 3000, -650, -130, 70, 1300], | |
interestRate: 1.2, // % | |
pin: 11411, | |
}; | |
const account2 = { | |
owner: 'Trevor Hanson', | |
movements: [50200, 3400, -150, -790, -3210, -1000, 8500, -30], | |
interestRate: 1.5, | |
pin: 2222, | |
}; | |
const account3 = { | |
owner: 'Grace Kelly', | |
movements: [2200, -200, 340, -300, -20, 50, 400, -460], | |
interestRate: 0.7, | |
pin: 3333, | |
}; | |
const account4 = { | |
owner: 'Rusty Shackleford', | |
movements: [4430, 1000, 700, 50, 90], | |
interestRate: 1, | |
pin: 4444, | |
}; | |
const accounts = [account1, account2, account3, account4]; | |
// output | |
// access accounts array | |
// flaten array | |
// get sum | |
const overallBalance = accounts | |
.map(acc => acc.movements) | |
.flat() | |
.reduce((acc, mov) => acc + mov, 0); | |
// 17840 | |
console.log(overallBalance); | |
// flatMap (better performance) | |
const overallBalance2 = accounts | |
.flatMap(acc => acc.movements) | |
.reduce((acc, mov) => acc + mov, 0); | |
// same result 17840 | |
console.log(overallBalance2); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment