简体   繁体   中英

How to add each set of numbers within an array of arrays? (javascript)

I'm struggling to design a loop that will cycle through an array of arrays and add each number together, work out the average then output to the console.

Here is my code;

 var data = [ [3, 6, 14, 17, 30, 40, 44, 66, 69, 84, 92, 95], [100, 17, 26, 28, 29, 34, 38, 59, 78, 82, 84, 93], [6, 12, 22, 25, 35, 44, 45, 57, 60, 61, 78, 80], [6, 11, 14, 19, 33, 50, 57, 58, 61, 88, 89, 97], [6, 13, 23, 28, 39, 44, 50, 55, 58, 72, 80, 88], [6, 8, 22, 26, 48, 50, 55, 65, 77, 84, 93, 99] ] var calcTotal, arrayTotal, totalSum; calcTotal = []; arrayTotal = []; totalSum = []; arrayTotal.push(data[0]) totalSum = data[0].reduce(function(a, b) { return a + b; }); calcTotal.push(totalSum) console.log(Math.round(totalSum / 12)) 

http://plnkr.co/edit/Ses4XApKEdo2CCZmsis7?p=preview

So far I have it working to display just one result, Ideally I would output the average from each array when added together in a single array to the console.

I've been playing around with for/forEach loops but can't seem to crack it, if anyone can offer some help/advice?

Thanks

It's pretty easy: you can write two functions, add and average , use Array#map and Array#reduce :

 var data = [ [3, 6, 14, 17, 30, 40, 44, 66, 69, 84, 92, 95], [100, 17, 26, 28, 29, 34, 38, 59, 78, 82, 84, 93], [6, 12, 22, 25, 35, 44, 45, 57, 60, 61, 78, 80], [6, 11, 14, 19, 33, 50, 57, 58, 61, 88, 89, 97], [6, 13, 23, 28, 39, 44, 50, 55, 58, 72, 80, 88], [6, 8, 22, 26, 48, 50, 55, 65, 77, 84, 93, 99] ]; function add(a, b) { return a + b; } function average(list) { return list.reduce(add) / list.length; } document.body.textContent = data.map(average); 

So as far as I understand you need to display to the console average of each row right?

You've done pretty good job with single line it just needed to be packed with forEach, here's working fiddle: https://jsfiddle.net/enowacki/dhdc1ztc/2/

 const data = [ [3, 6, 14, 17, 30, 40, 44, 66, 69, 84, 92, 95], [100, 17, 26, 28, 29, 34, 38, 59, 78, 82, 84, 93], [6, 12, 22, 25, 35, 44, 45, 57, 60, 61, 78, 80], [6, 11, 14, 19, 33, 50, 57, 58, 61, 88, 89, 97], [6, 13, 23, 28, 39, 44, 50, 55, 58, 72, 80, 88], [6, 8, 22, 26, 48, 50, 55, 65, 77, 84, 93, 99] ]; const result = data.map((arr) => { const rowSum = arr.reduce((prev, curr) => prev + curr); const rowCount = arr.length; const avg = Math.round(rowSum / rowCount); return avg; }); console.log(result); 

I've extracted some additional variables so you can clearly see what's going on feel free to omit them if not needed.

Flatten:

var flat = [].concat.apply([], data);

Sum:

var sum = flat.reduce((a, b) => a+b, 0);
console.log("Avg:" + Math.round(sum / flat.length);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM