-
Notifications
You must be signed in to change notification settings - Fork 0
/
arrayAverageSum.js
43 lines (28 loc) · 1.3 KB
/
arrayAverageSum.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// Program a function sumAverage(arr) where arr is an array containing arrays full of numbers, for example:
// sumAverage([[1, 2, 2, 1], [2, 2, 2, 1]]);
// First, determine the average of each array. Then, return the sum of all the averages.
// All numbers will be less than 100 and greater than -100.
// arr will contain a maximum of 50 arrays.
// After calculating all the averages, add them all together, then round down, as shown in the example below:
// The example given: sumAverage([[3, 4, 1, 3, 5, 1, 4], [21, 54, 33, 21, 77]]), the answer being 44.
// Calculate the average of each individual array:
// [3, 4, 1, 3, 5, 1, 4] = (3 + 4 + 1 + 3 + 5 + 1 + 4) / 7 = 3
// [21, 54, 33, 21, 77] = (21 + 54 + 33 + 21 + 77) / 5 = 41.2
// Add the average of each array together:
// 3 + 41.2 = 44.2
// Round the final average down:
// Math.floor(44.2) = 44
// import math
// math.floor(44.2) = 44
const sumAverage = (arr) => {
const result = arr.map(e => e.reduce((acc,val) => acc + val,0)/e.length).reduce((acc,val) => acc + val ,0);
return Math.floor(result);
}
console.log(sumAverage([[3, 4, 1, 3, 5, 1, 4], [21, 54, 33, 21, 77]]));
//cw's
function sumAverage2(arr) {
return Math.floor(arr
.map(e => e.reduce(sum) / e.length)
.reduce(sum));
}
const sum = (a, b) => a + b;