findAverage.js (8kyu 05)
Codewars 알고리즘 풀이
Description
- Write a function 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]); // 2
findAverage([1, 2, 3, 4]); // 2.5
findAverage([2, 2, 2, 2]); // 2
Solution 02
function findAverage(arr) {
return arr.reduce((sum, i) => sum + i, 0) / arr.length;
}
findAverage([1, 2, 3]); // 2
findAverage([1, 2, 3, 4]); // 2.5
findAverage([2, 2, 2, 2]); // 2