본문 바로가기
알고리즘/Codewars

[Codewars] Calculate average (8 kyu) / JavaScript

by fluss 2022. 11. 3.

https://www.codewars.com/kata/57a2013acf1fa5bfc4000921

 

Codewars - Achieve mastery through coding practice and developer mentorship

A coding practice website for all programming levels – Join a community of over 3 million developers and improve your coding skills in over 55 programming languages!

www.codewars.com

 

DESCRIPTION:

Write a function which calculates the average of the numbers in a given list.

Note: Empty arrays should return 0.

 

설명:

주어진 리스트에 있는 숫자들의 평균을 계산하는 함수를 작성하세요. 

참고: 빈배열은 0을 반환해야 합니다.

 

풀이

배열이 null이거나 배열의 크기가 1보다 작을 때는 0을 반환해주고 그렇지 않을 경우는 reduce를 사용해서 배열의 모든 원소를 더하고 배열의 길이로 나누어준다.

 

코드

function findAverage(array) {
  if(array === null || array.length < 1) return 0;
  return array.reduce((acc, cur) => acc + cur, 0) / array.length;
}

댓글