Skip to content

Instantly share code, notes, and snippets.

@kironroy
Last active June 29, 2023 01:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kironroy/9c5609461d0824f2637898356951ffe7 to your computer and use it in GitHub Desktop.
Save kironroy/9c5609461d0824f2637898356951ffe7 to your computer and use it in GitHub Desktop.
map and multi-dim arrays
// 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