I need to finish a function that starts:
function organizeItems(items) {
I need to finish that to organize a list of categories. my categories are fruit, dairy, and canned. My code looks like this:
[
{ category: 'fruit', itemName: 'oranges', onSale: false },
{ category: 'dairy', itemName: 'milk($)', onSale: true },
{ category: 'canned', itemName: 'peas', onSale: false },
{ category: 'canned', itemName: 'green beans($)', onSale: true },
{ category: 'fruit', itemName: 'grapes($)', onSale: true },
{ category: 'canned', itemName: 'carrots', onSale: false },
];
So how do I function this to return a list like:
{
fruit: ['apple', 'melon($)'],
canned: ['beans', 'corn($)', 'soup'],
frozen: ['pizza']
};
I would do this via the reduce function:
const items=[{category:'fruit',itemName:'oranges',onSale:false},{category:'dairy',itemName:'milk($)',onSale:true},{category:'canned',itemName:'peas',onSale:false},{category:'canned',itemName:'green beans($)',onSale:true},{category:'fruit',itemName:'grapes($)',onSale:true},{category:'canned',itemName:'carrots',onSale:false},];
const categorised = items.reduce((a, { category, itemName }) => {
a[category] = a[category] || [];
a[category].push(itemName);
return a;
}, {});
console.log(categorised);
.as-console-wrapper {
max-height: 100% !important;
top: auto;
}
This works by getting the category name and item name of each item in the initial array, and then initialising each category name to be an empty array within the accumulator object. Then push the item name to the corresponding category array (either pre-existing or empty), and you're done!