JS_HOME_WORK/48-reduce-to-object/solution.js
2025-01-17 01:00:07 +01:00

53 lines
1.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/** ЗАДАЧА 48 - Использование метода "reduce" для создания объекта
*
* 1. Создайте функцию "quantitiesByCategories" с одним параметром "products"
*
* 2. Эта функция должна возвращать объект с ключами,
* равными категориям, и значениями,
* равными сумме всех количеств в каждой категории
*/
function quantitiesByCategories(products) {
return products.reduce((qtysByCategories, product) => {
const { category, quantity } = product
qtysByCategories[category] = (qtysByCategories[category] || 0) + quantity
return qtysByCategories
}, {})
}
const inputProducts = [
{
title: 'Phone case',
price: 23,
quantity: 2,
category: 'Accessories',
},
{
title: 'Android phone',
price: 150,
quantity: 1,
category: 'Phones',
},
{
title: 'Headphones',
price: 78,
quantity: 1,
category: 'Accessories',
},
{
title: 'Sport Watch',
price: 55,
quantity: 2,
category: 'Watches',
},
]
console.log(quantitiesByCategories(inputProducts))
/* {
Accessories: 3,
Phones: 1,
Watches: 2
} */