자바스크립트 평균값 구하기 with reduce

IT쿠키·2022년 9월 20일
1
post-thumbnail

자바스크립트 평균값 구하기

(프로그래머스 코딩 테스트 평균 구하기 1레벨이다)
간단하게 reduce() 함수를 사용해서 간단하게 풀어보자

function solution(arr) {
  const result =
    arr.reduce((item, cuurentValue) => item + cuurentValue) / arr.length;
  return result;
} 

let testarray = solution([1,2,3,4]);
console.log("평균 값 :"  + testarray )

reudce 로 배열의 합을 구하고 그 이후 배열의 갯수 만큼 나눈 후 평균값을 구해냈다.

reduce 함수

reduce()** 배열의 모든 요소들에 대하여 연산을 수행한 다음에 하나의 결과 값을 리턴 한다.

예를 들면
let arr = [1,2,3,4]
이런 식에 배열이 있다고 치고 arr.reduce(a+b)를 하게 된다면
//(1 + 2 + 3+ 4) => 결과는 10이 나오게 되는 데
한번에 더해서 10이 나오는 게 아닌 1 + 2를 한 후 그 결과인 3을 다음 요소인 3과 합하고 나서 6을 가지고 맨 마지막 요소 4와 더해 10이라는 값이 나온다.

리듀서 함수는 네개의 인자를 가져 오는데

  1. accumulator : accumulator는 callback 함수의 반환 값을 누적 해줍니다.
  2. currentValue : 배열의 현재 요소 값
  3. index(Optional) : 배열의 현재 요소의 인덱스 값
  4. array(Optional) : 호출한 배열

initialValue(Optional)

최초의 callback 함수 실행시 accumulator 인수에 제공되는 값, 초기값을 제공하지 않을 경우 배열의 첫번째 요소를 사용하고, 빈 배열에서 초기값이 없다면 에러를 발생시키빈다.

기본 값
function reduceArray(accumulator, currentValue, currentIndex, array)
가 기본 형태인데 뒤에 두개는 옵셔널이라 선택적 사항이다.

반환값

배열의 순서대로 불러 각 요소에 대한 callback 함수를 실행한 결과를 누적해준다.
여기서 기초적인 전부다 불러오는 reduce() 함수를 불러오면

const arr = [1, 2, 3, 4];

function reduceArray(accumulator, currentValue, currentIndex, array) {
  console.log("accumulator: " + accumulator + ", currentValue: " + currentValue
    + ", currentIndex: " + currentIndex + ", array: " + array);
  return accumulator + currentValue;
}

const initialValue = 0;
const sumWithInitial = arr.reduce(reduceArray, initialValue);

// 0 + 1 + 2 + 3 + 4
console.log(sumWithInitial);

가 기본적인 구조가 된다.
근데 여기서 옵셔널인거 두개를 제외하면

const arr = [1, 2, 3, 4];

function reduceArray(accumulator, currentValue) {
  console.log("accumulator: " + accumulator + ", currentValue: " + currentValue);
  return accumulator + currentValue;
}

const initialValue = 0;
const sumWithInitial = arr.reduce(reduceArray, initialValue);

// 0 + 1 + 2 + 3 + 4
console.log(sumWithInitial);

로도 같은 값이 나오게 된다:)

profile
IT 삶을 사는 쿠키

0개의 댓글