TIL_2305026 - 프로그래머스 - Lv1. 음양 더하기(reduce)

정윤숙·2023년 5월 26일
0

TIL

목록 보기
160/192
post-thumbnail

📒 오늘의 공부

1. 프로그래머스

Lv1. 음양 더하기

나의 풀이

const solution=(absolutes, signs)=> {
    let answer = 0;
    for(let i=0; i<signs.length; i++){
        signs[i] ? answer+=absolutes[i] : answer-=absolutes[i]
    }
    return answer
}

다른 풀이

function solution(absolutes, signs) {

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

reduce()

arr.reduce(callback[, initialValue])

  • reduce()는 빈 요소를 제외하고 배열 내에 존재하는 각 요소에 대해 callback 함수를 한 번씩 실행
  • 4개의 인자
    • 누산기 (acc) - 콜백의 반환값 누적
    • 현재 값 (cur)
    • 현재 인덱스 (idx) - initialValue를 제공한 경우 0 or 1
    • 원본 배열 (arr)

참고 자료

mdn reduce함수

profile
프론트엔드 개발자

0개의 댓글