알고리즘 22 - Get the mean of an array

jabae·2021년 10월 18일
0

알고리즘

목록 보기
22/97

Q.

t's the academic year's end, fateful moment of your school report. The averages must be calculated. All the students come to you and entreat you to calculate their average for them. Easy ! You just need to write a script.

Return the average of the given array rounded down to its nearest integer.

The array will never be empty.

A)

function getAverage(marks){
  let result = 0;
  
  for (let el of marks)
    result += el;
  
  return Math.floor(result/marks.length)
}

other

오잉! .reduce는 뭐지! .map으로 하고 싶었는데 안될 것 같아서 for문으로 했는데 이 녀석!! 짧다! 누적값으로 하나의 결과값을 반환해서 이렇게 배열의 모든 값을 더할 때 많이 쓰인다고 한다.

function getAverage(marks){
  return Math.floor(marks.reduce((sum, x) => sum + x) / marks.length);
}
profile
it's me!:)

1개의 댓글

comment-user-thumbnail
2021년 10월 19일

이거 오늘 배우겠네요 리듀스 생각보다 어렵지만 익숙해지면 정말 편하고 간편하고 짱인 메서드임다.

답글 달기