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

Create a array of objects by grouping objects conditionally

I am trying to create a new array of objects by comparing two arrays.One array contains the ids to be compared and the other contains the dataset which should be compared with the first array are a new array of object must be created.

Let me explain this in detail

Consider array 1:

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

['1','2']

Array 2

[{name:'Linus',id:'1'},{name:'Anthony',id:'1'},{name:'Jake',id:'2'},{name:'Eva',id:'2'}]

What I am expecting as a output is:

[
{id:'1',users:[{name:'Linus',id:'1'},{name:'Anthony',id:'1'}]},
{id:'2',users:[{name:'Jake',id:'2'},{name:'Eva',id:'2'}
]

I am not sure what has to be done.

>Solution :

Something like this for example

const ids = ['1','2'];
const users = [{name:Linus,id:'1'},{name:Anthony,id:'1'},{name:Jake,id:'2'},{name:Eva,id:'2'}];

const groups = ids.map(id =>{
    return {
        id,
        users: users.filter(u => u.id === id)
    }
})
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