Skip to content
Advertisement

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.

Update:

Thanks to flyingfox for solving my issue. But I see that if i have duplicate value in array1 the array2 doenst include it multiple time.

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

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

here array2=[{id:1}, {id:3}]
But I want to get the duplicate as well. 
Like array2=[{id:1}, {id:3}, {id:3}, {id:3}] as array1 has 3 multiple time

Advertisement

Answer

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)
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement