반응형
Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

undefined

[프로그래머스] 음양 더하기 -JS 본문

카테고리 없음

[프로그래머스] 음양 더하기 -JS

JavaScripter 2022. 6. 8. 20:29
반응형

문제 설명


문제 풀이

function solution(absolutes, signs) {
    const array = absolutes.map(function(e,i) {
        if(!signs[i]) {
            return Math.abs(e)*-1
        } else {
            return e
        }
    })
    return array.reduce((p,c) => p+c)
}

1. map의 index인자로 signs와 연결

 

2. signs가 false 일때 Math.abs(e)*-1로 minus화 하여 리턴

 

3. reduce로 모두의 합 구하기


개선 사항

function solution(absolutes, signs) {

    return absolutes.reduce((acc, val, i) => acc + (val * (signs[i] ? 1 : -1)), 0);
}

1. reduce의 삼항연산자 활용(+index)

 

반응형
Comments