Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

147
Views
function that organizes items by category

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']
};
about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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!

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!