I have an array of objects such as this:
var arr = [
{name:"item1", category:0},
{name:"item2", category:3},
{name:"item3", category:1},
{name:"item4", category:1},
]
I want to produce a multi-dimensional array based on category values such as this: (We can assume fixed length, i.e. no category 4)
var arr2 = [
[{name:"item1", category:0}],
[{name:"item3", category:1},{name:"item4", category:1}],
[],
[{name:"item2", category:3}]
]
My current solution is this:
var arr2 = [[],[],[],[]];
arr.forEach(x => {
arr2[x.category].push(x);
});
But I’m looking for a more JavaScript-y way (with map, filter etc) and preferrably a one-liner.
Thanks for any help!
>Solution :
Your one-liner: create an array with Array.from() with length of maximum category ID plus 1, and map elements with filtered arrays by the index category :
var arr = [
{name:"item1", category:0},
{name:"item2", category:3},
{name:"item3", category:1},
{name:"item4", category:1},
]
const result = Array.from({length: Math.max(...arr.map(item => item.category)) + 1}, (_, idx) => arr.filter(({category}) => category === idx));
console.log(result);