Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to map JavaScript array to multidimensional array based on item property?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading