Home > Back-end >  Finding data from one array by looping another array (MongoDB, Javascript)
Finding data from one array by looping another array (MongoDB, Javascript)

Time:12-06

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.

CodePudding user response:

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)

  • Related