문제
메모
// 배열 속 객체 요소의 합
const objects = [{ x: 1 }, { x: 2 }, { x: 3 }];
const sum = objects.reduce((acc, cur) => acc + cur.x, 0); // 초기값 0 필수
console.log(sum); // 6
정답
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" },
];
const productsByCategory = products.reduce((acc, cur) => {
if (acc[cur.category] === undefined) {
acc[cur.category] = [];
}
acc[cur.category].push(cur);
return acc;
}, {});
const avgPriceByCategory = Object.keys(productsByCategory).map(x => {
const sum = productsByCategory[x].reduce((acc, cur) => acc + cur.price, 0);
return { category: x, average: sum / productsByCategory[x].length };
});
console.log(avgPriceByCategory);
반응형