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

[Codewars] Sum of positive (8 kyu) / JavaScript

by fluss 2022. 11. 10.

https://www.codewars.com/kata/5715eaedb436cf5606000381

DESCRIPTION:

You get an array of numbers, return the sum of all of the positives ones.

Example [1,-4,7,12] => 1 + 7 + 12 = 20

Note: if there is nothing to sum, the sum is default to 0.

 

설명:

숫자로 이루어진 배열을 받고 그 배열의 모든 양수의 합을 구해서 반환하세요

예: [1,-4,7,12] => 1 + 7 + 12 = 20

참고: 합칠 것이 없으면 그 합계의 기본값은 0입니다.

 

풀이

reduce로 값이 0보다 클 때는 그 값을 더해주고 그렇지 않을 때는 0을 더해서 답을 구하였다.

 

코드

function positiveSum(arr) {
  return arr.reduce((acc, cur) => {
    if(cur > 0) return acc + cur;
    else return acc + 0;
  }, 0)
}

 

댓글