undefined
[프로그래머스] 음양 더하기 -JS 본문
반응형
문제 설명
문제 풀이
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