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

144
Visualizações
how can i get the function to return me an object with categories?

So, im trying to classify objects of food category or tech category, as an object by categories as a final result. I have this input for the arguments in my function and then my end result should return me an object with both

{
 tech:  [ { tech product }, { tech product } ],
 food:  [ { food product }, { food product } ],
}

So what i have is a function where i try to construct an array with objects classifying the products. So far this is what i have been able to develop is this code, but for some reason I only get it to return me an empty object, not an object with both categories as I'm trying to.

function sortProducts (matrix) {
  const matrixResult = {};
  for (i = 0; i < matrix.length; i++){
    let techProd = matrix[i];
    let techCategory = matrix[i].category;
    let techCategFilter = techCategory === ‘tech’;
    if (techCategFilter){
      let arrTech = []
      arrTech.push (techProd[i]);
      matrixResult.tech = arrTech;
    }
  }
   for (i = 0; i < matrix.length; i++){
    let foodProd = matrix[i];
    let foodCategory = matrix[i].category;
    let foodCategFilter = foodCategory === ‘food’;
    if (foodCategFilter){
      let arrFood = []
      arrFood.push (foodProd[i]);
      matrixResult.food = arrFood;
    }
  }
  return matrixResult;
}

What am i missing or where am i messing up?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Use reduce or filter, depending on how big your array is. I decided on forEach, since it is easier to read.

const result = {};

products.forEach(product => {
  const category = product.category;
  if (result[category]) {
    result[category].push(product);
  } else {
    result[category] = [product];
  }
})
about 4 years ago · Juan Pablo Isaza Relatório

0

I see multiple issues with this code.

  1. arrFood and arrTech arrays are initialized every time in loop so older objects pushed are getting overwritten every time in the if block and you will have only 1 object max always.
  2. foodProd = matrix[i] will give you the food product object but then you push foodProd[i] to array which i guess will be undefined.

Try this (fixed the above issues and also shorten little bit):

function sortProducts (matrix) {
  const matrixResult = { tech: [], food: []};

  for (i = 0; i < matrix.length; i++){
    let techProd = matrix[i];
    if (techProd.category === 'tech'){
      matrixResult.tech.push (techProd);
    }
  }
   for (i = 0; i < matrix.length; i++){
    let foodProd = matrix[i];
    if (foodProd.category === 'food'){
      matrixResult.food.push (foodProd);
    }
  }
  return matrixResult;
}

you can as well use forEach instead of looping or reducer as suggested by @HPSingh.

forEach example:

var matrixResult = { tech: [], food: []};
matrix.forEach( obj => {
  if(obj.category === 'food') matrixResult.food.push(obj);
  else if(obj.category === 'tech') matrixResult.tech.push(obj);
});
about 4 years ago · Juan Pablo Isaza Relatório

0

So after checking with a colleague he recommended this which worked very well

function sortProducts (matrix) {
  const tech = [];
  const food = [];
  
  for (let i = 0; i < matrix.length; i++) {
    const arr = matrix[i];

    for (let j = 0; j < arr.length; j++) {
      const product = arr[j];
      
      if ( product.category === 'tech') {
        tech.push(product);
      } else if (product.category === 'food') {
        food.push(product);
      }
    };
  };  
  
  return {
    tech: tech,
    food: food,
  }
}
about 4 years ago · Juan Pablo Isaza 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