- 설명
- 예시1
- 예시2
1. 설명
Array.prototype.reduce()
reduce() 메서드는 배열의 각 요소에 대해 주어진 리듀서 (reducer) 함수를 실행하고, 하나의 결과값을 반환합니다.라고 mdn web doc에 나와있습니다. 값이 나열 되어있는 배열에서, 한 값을 도출 할 때 사용하면 유용하다 것으로 인식 하면 될 듯합니다참고 : https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce2. 예시1
const array1 = [1, 2, 3, 4];
// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
(accumulator, currentValue) => accumulator + currentValue,
initialValue
);
console.log(sumWithInitial);
// Expected output: 103. 예시2 (객체 배열)
const products = [
{ name: "Product 1", price: 10 },
{ name: "Product 2", price: 20 },
{ name: "Product 3", price: 30 },
{ name: "Product 4", price: 40 }
];
const total = products.reduce((accumulator, currentValue) => {
return accumulator + currentValue.price;
}, 0);
console.log(total); // 100reduce에 대해서 간단하게 기재했습니다. reduce모르고 작업을 했던 시간이 아까울 만큼 사용처가 많은 메소드 라고 생각합니다. Array.reduce말고 더 많은 메소드와 개발 방법이 존재한다고 생각하니까, 요즘 공부에 소홀했구나 라는 생각이 듭니다. 지식을 채운 만큼 효율적으로 코딩하긴 좋은 것은 부정 할 수 없군요..