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

185
Vistas
How do I return an object from a function?

I ran into this challenge for my course which i cannot crack for the life of me.

You are given a function with a single parameter which is a nested array with objects.

function sortProducts (matrix) `enter code here`

The array (matrix) looks like this:

[
  [
    { product: "MacBook", price: 1019, category: 'tech'},
    { product: "Cheerios", price: 5, category: 'food'},
  ],

  [
    { product: "Snickers", price: 1.5 , category: 'food'},
    { product: "Air Pods", price: 129, category: 'tech'},
  ],

];

Instructions: Inside the matrix array, each nested array holds objects. Each object represents a product.

The function should loop over the matrix and create a new object containing the products sorted by their category. The function should then return back this result object containing sorted products, stored in properties tech and food.

The result object should have the following structure:

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

So from my understanding the first step would be to loop over the array to create this new object. This objected would have to sort the products by category in the format (tech: 'tech product', food: 'food product'.

I know the answer is going to be so simple but i cant do it for the life of me.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

One way would be to flatten the array first using flatMap() and then use reduce to group by category. Here is an example:

let arr = [
  [
    { product: "MacBook", price: 1019, category: 'tech'},
    { product: "Cheerios", price: 5, category: 'food'},
  ],

  [
    { product: "Snickers", price: 1.5 , category: 'food'},
    { product: "Air Pods", price: 129, category: 'tech'},
  ],

]

let result = arr.flatMap(i => i).reduce((c, p) => {
  c[p.category] = c[p.category] || [];
  c[p.category].push(p);
  return c;
}, {});

console.log(result)

about 4 years ago · Juan Pablo Isaza Denunciar

0

I don't understand why its called "sortProducts", your no sorting your just parsing or converting the input to another object.

Try something like this:

function sortProducts(matrix){

    var result = {};

  for (let i = 0; i < matrix.length; i++) {
    const arr = matrix[i];
    
    for (let j = 0; j < arr.length; j++) {
      const obj = arr[j];

      var newObj = { product: obj.product, price: obj.price};
      
      // If result already has the category then just push the new object
      if (result[obj.category]) {
        result[obj.category].push(newObj);
        continue;
      }

      // Otherwise add the category and add the object inside an array
      // This automaticly ensures that the result.category is an array
      result[obj.category] = [newObj];

    }

  }

  return result;
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

So the solution was even simpler than i thought :'(

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,
  }
}

I have no idea how I didnt figure that one out. Hopefully can continue this learning curve.

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