findAverage.js (8kyu 17)
Codewars 알고리즘 풀이
Problem
- Write function findAverage() which calculates average of numbers in given list.
- 배열 내 숫자의 평균을 반환한다.
Solution 01
function findAverage(arr) {
let sum = 0;
for (let i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum / arr.length;
}
findAverage([1, 2, 3, 4]); // 2.5 (10 / 4)
findAverage([1, 2, 3, 4, 5]); // 3 (15 / 5)
findAverage([88, 92, 96, 100]); // 94 (376 / 4)
Solution 02
function findAverage(arr) {
let sum = arr.reduce((result, i) => result + i, 0);
return sum / arr.length;
}
findAverage([1, 2, 3, 4]); // 2.5 (10 / 4)
findAverage([1, 2, 3, 4, 5]); // 3 (15 / 5)
findAverage([88, 92, 96, 100]); // 94 (376 / 4)
reduce()
메소드배열을 하나의 값으로 줄이고, 그 값을 반환한다.