array내 숫자들의 평균값을 구하는 문제였다.
먼저 array 내 숫자들의 합을 구하고 (reduce 함수 사용)
그 합을 array의 길이로 나눠주면 되는 순서다. (.length 사용)
mdn_reduce 함수 설명
reduce 는 array 합을 구해주는 함수.
const array1 = [1, 2, 3, 4];
// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
(accumulator, currentValue) => accumulator + currentValue,
initialValue
);
console.log(sumWithInitial);
// expected output: 10
간단한 수식으로 정리하면,
a = accumulator (누산기 : 축적될 값)
b = currentValue (현재 값 : 더해줄 값)
0 = initialValue (초기값)
reduce((a,b) => a + b, 0)
.length
사용하기let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
sum = numbers.reduce((a,b) => a + b, 0)
return(sum/numbers.length) // 5.5
for ~ of 사용
내가 처음에 시도했다가 실패했던 수식의 성공 버전