Issue
This Content is from Stack Overflow. Question asked by Niko Nota
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 } ],
}
Solution
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))
This Question was asked in StackOverflow by Niko Nota and Answered by jsN00b It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.