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;
}
'알고리즘 > Codewars' 카테고리의 다른 글
[Codewars] Stop gninnipS My sdroW! (6 kyu) / JavaScript (0) | 2022.11.05 |
---|---|
[Codewars] If you can't sleep, just count sheep!! (8 kyu) / JavaScript (0) | 2022.11.04 |
[Codewars] The Supermarket Queue (6 kyu) / JavaScript (0) | 2022.11.02 |
[Codewars] Count of positives / sum of negatives (8 kyu) / JavaScript (0) | 2022.11.01 |
[Codewars] Friend or Foe? (7 kyu) / JavaScript (0) | 2022.10.31 |
댓글