Q:

Write a JavaScript program to get the sum of a given array, after mapping each element to a value using the provided function

0

Write a JavaScript program to get the sum of a given array, after mapping each element to a value using the provided function.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

const sumBy = (arr, fn) =>
arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => acc + val, 0);

console.log(sumBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n));
console.log(sumBy([{ n: -4 }, { n: -2 }, { n: 8 }, { n: 6 }], 'n'));

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now