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

Finding data from one array by looping another array (MongoDB, Javascript)

I have 2 arrays.

array1 = [1, 2, 3]
array2 = [{id:1}, {id:1}, {id:3}]

I want to get an array of objects with same id. Like when I go get all the object of 1 then I will loop through array2 and get the object then put them in a 3rd array.

I’m stuck at this point.

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

>Solution :

If you just want to put all elements with same id into a new array,then below is a reference for you

let array1 = [1, 2, 3]
let array2 = [{id:1}, {id:1}, {id:3},{id:4}]

array1 = array1.filter(e1 => array2.some(e2 => e2.id === e1))
array2 = array2.filter(e1 => array1.some(e2 => e2 === e1.id))

let array3 = [...array1,...array2]
console.log(array3)
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