본문 바로가기
알고리즘 문제

배열의 평균값

by rinny01 2024. 11. 27.
반응형

문제

정수 배열 numbers가 매개변수로 주어집니다. numbers의 원소의 평균값을 return하도록 solution 함수를 완성해주세요.

풀이

function solution(numbers) {
    var answer = 0;
    numbers.forEach(a=>{
        answer += a;
    })
    return answer / numbers.length;
}
console.log(solution([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))

다른풀이

reduce() 사용하기
arr.reduce(callback[, initialValue])

 

어떤 배열의 reduce()메서드를 호출하면 배열을 상대로 각 요소인자로 넘어온 콜백함수를 실행하여 누적된 하나의 결과값을 반환한다.

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

 

 

완전함수 대신에 화살표 함수도 사용 가능하다.

[0, 1, 2, 3, 4].reduce((prev, curr) => prev + curr);

 

 

reduce() 를 이용하여 배열의 평균값 구하기

 

function solution(numbers) {
    var answer = numbers.reduce((sum, number) => {
        return sum + number;
    },0) // 초기값 0 설정
    return answer / numbers.length;
}
console.log(solution([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))

 

반응형
LIST

'알고리즘 문제' 카테고리의 다른 글

[프로그래머스]x만큼 간격이 있는 n개의 숫자_js  (2) 2024.12.24
Javascript 자릿수 더하기  (2) 2024.11.28
짝수의 합  (3) 2024.11.25
각도기 (if문)  (0) 2024.11.22
정수로 반환하기  (0) 2024.11.19