Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

143
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda