Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

149
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda