[codewars] Sum of positive

KJA·2022년 8월 18일
0

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.

문제 해결

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

다른 풀이

if문을 3항 연산자로 구현

function positiveSum(arr) {
   return arr.reduce((a,b)=> a + (b > 0 ? b : 0),0);
}

0개의 댓글

관련 채용 정보