Home > Net >  How to loop through my array matrix and create an object containing items by their category
How to loop through my array matrix and create an object containing items by their category

Time:09-19

So I created the following:

I made this matrix array, each nested array has objects:

[
  [
    { category: 'tech', product: "iPhone X", price: 320 },
    { category: 'food', product: "Cheerios", price: 5 },
  ],

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

]

Then, I created this function that loops through the array matrix:

function sortProducts (matrix) {
  for (x=0;x<matrix.length;x  ) {      
      for (y=0;y<matrix[x].length;y  ){ 
         console.log(matrix[x][y]);     
    }  
  }
}

Now, Im just trying to figure out how to create and return a new object containing the products sorted by their category like this:

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

CodePudding user response:

Flatten and reduce...

const data = [
  [
    { category: 'tech', product: "iPhone X", price: 320 },
    { category: 'food', product: "Cheerios", price: 5 },
  ],

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

const flat = arr => arr.reduce((acc, el) => acc.concat(el),[]);

function sortProducts(matrix) {
  return flat(matrix).reduce((acc, obj) => {
    let cat = obj.category;
    if (!acc[cat]) acc[cat] = [];
    acc[cat].push(obj);
    return acc;
  }, {});
}

console.log(sortProducts(data))

flat() (doc) note the availability section in that doc promotes objects contained in nested arrays to the top level of the outer array. (We don't need the column structure to index by category). reduce() (doc) just iterates that flattened array, passing an object between iterations. The object category is used as the key, and the values are arrays. acc[cat].push(obj); pushes the object to the array whose key is the category.

CodePudding user response:

we can achieve this way too

const data = [
  [
    { category: 'tech', product: "iPhone X", price: 320 },
    { category: 'food', product: "Cheerios", price: 5 },
  ],

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

const fun = (ar)=>{
 var obj ={}
const mix = ar.flatMap((el ,i)=> el)
for (let[i, e] of Object.entries(mix)){
  let sep = e.category
!obj[sep] ? obj[sep]=[e] : obj[sep].push(e)
}
 return obj
}
console.log(fun(data))

  • Related