1

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.

Abid
  • 11
  • 1
  • 3
    What did you try so far? Show us your code attempt. – accdias Jun 30 '22 at 17:02
  • Check [_How to loop through an array containing objects and access their properties_](https://stackoverflow.com/questions/16626735/how-to-loop-through-an-array-containing-objects-and-access-their-properties), and use it as starting point. – accdias Jun 30 '22 at 17:06
  • Everything I have tried just throws me errors. I tried a for loop. for in loop. Currently tried a forEach loop but I have no idea how to return a filtered object. – Abid Jun 30 '22 at 17:12
  • this looks like assignment – Rahul R. Jun 30 '22 at 17:25

4 Answers4

1

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)
Timur
  • 1,682
  • 1
  • 4
  • 11
  • This is javascript fundamentals so I doubt theyd expect us to use something like flatMap at this stage. – Abid Jun 30 '22 at 17:25
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;
}
Filipe Nóbrega
  • 564
  • 4
  • 18
  • It still returns a fail, but passes 3 out of 4 tests. the test it fails is : should return an object with two properties "tech" and "food", each having products sorted by category. I will try to work this one out but i appreciate the help a lot. – Abid Jun 30 '22 at 17:21
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.

Abid
  • 11
  • 1
0

Here is an alternative solution:

function sortCart(cart) {
  let sortedCart = {}
  cart.forEach((items) => {
    items.forEach((item) => {
      if (!sortedCart[item.category]) {
        sortedCart[item.category] = []
      }
      sortedCart[item.category].push(item)
    })
  })
  return sortedCart
}


let cart = [
  [
    { 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'},
  ],
]

console.log(sortCart(cart))
accdias
  • 5,160
  • 3
  • 19
  • 31