반응형
JavaScript array에는 유용한 함수들이 많습니다.
자세한 내용은 여기를 참고하세요.
reduce()
: reduce 메서드는 호출된 배열의 모든 element를 대상으로 reducer 함수를 실행한 결과 값을 반환합니다. 보통 누산기로 사용하기 좋습니다.
Syntax: reduce(reducer함수, 초기값)
const sourceArray = [1, 2, 3];
// reducer 함수를 arrow function으로 대체한 형태
const initValue = 0
const reduceValue1 = sourceArray.reduce(
(acc, curr) => acc + curr,
initValue
);
// 결과값: 6
console.log(reduceValue1);
// reducer 함수를 따로 빼서 적용한 형태
const reducer = function(acc, curr, idx) {
acc += curr
return acc
}
const reduceValue2 = sourceArray.reduce(
reducer,
initValue
);
// 결과값: 6
console.log(reduceValue2);
반응형
'WEB > JS|Node.js' 카테고리의 다른 글
Mac에서 homebrew를 이용해 Node.js LTS버전 설치하기 (0) | 2022.09.06 |
---|---|
JavaScript Operator - Spread & Rest (0) | 2022.08.31 |
JS Array functions (4) - concat() (0) | 2022.08.28 |
JS Array functions (3) - slice(), splice() (0) | 2022.08.28 |
JS Array functions (2) - find(), findIndex() (0) | 2022.08.28 |