메모
- reduce는 누적 계산값(prev)에서 현재값(cur)을 더해가는 방식으로 작동한다.
- 0은 초기값으로 생략해도 무관하다. 초기값을 설정하지 않으면 arr의 첫 번째 값이 들어간다.
예시
// arr의 합계
let arr = [1, 2, 3, 4, 5];
let result = arr.reduce((prev, cur) => {
return prev + cur;
}, 0);
console.log(result); // 15
// 현재 객체의 price가 50보다 크면 name만 반환하기
const products = [
{ name: "Product 1", price: 20, category: "Electronics" },
{ name: "Product 2", price: 30, category: "Clothes" },
{ name: "Product 3", price: 40, category: "Electronics" },
{ name: "Product 4", price: 50, category: "Clothes" },
{ name: "Product 5", price: 60, category: "Clothes" },
{ name: "Product 6", price: 70, category: "Electronics" },
{ name: "Product 7", price: 80, category: "Clothes" },
{ name: "Product 8", price: 90, category: "Electronics" },
];
let result = products.reduce((prev, cur) => {
if (cur.price > 50) {
prev.push(cur.name);
}
return prev;
}, []);
console.log(result); // [ 'Product 5', 'Product 6', 'Product 7', 'Product 8' ]
// 현재 객체의 category가 "Electronics"면 name을 반환
const products = [
{ name: "Product 1", price: 20, category: "Electronics" },
{ name: "Product 2", price: 30, category: "Clothes" },
{ name: "Product 3", price: 40, category: "Electronics" },
{ name: "Product 4", price: 50, category: "Clothes" },
{ name: "Product 5", price: 60, category: "Clothes" },
{ name: "Product 6", price: 70, category: "Electronics" },
{ name: "Product 7", price: 80, category: "Clothes" },
{ name: "Product 8", price: 90, category: "Electronics" },
];
let result = products.reduce((prev, cur) => {
if (cur.category === "Electronics") {
prev.push(cur.name);
}
return prev;
}, []);
console.log(result); // [ 'Product 1', 'Product 3', 'Product 6', 'Product 8' ]