January 2020
Intermediate to advanced
470 pages
11h 13m
English
What would you do if, instead of a single value, you needed to calculate two or more results? This would seem to be a case for providing a clear advantage for common loops, but there's a trick that you can use. Let's yet again revisit the average calculation. We might want to do it the old-fashioned way, by looping and at the same time summing and counting all numbers. Well, reduce() only lets you produce a single result, but there's no reason you can't return an object with as many fields as desired:
const average3 = arr => { const sumCount = arr.reduce( (accum, value) => ({sum: value + accum.sum, count: accum.count + 1}), {sum: 0, count: 0} ); return sumCount.sum / sumCount.count;};console.log(average3(myArray) ...Read now
Unlock full access