Home > Back-end >  how to cross section 2 arrays in javascript, by comparing id?
how to cross section 2 arrays in javascript, by comparing id?

Time:03-20

i have 2 arrays of objects with the same structure , each one of them came from database query, how i can map the cross section into a new array by comparing the ID value.

tempArray=[{city:london,subject:"testdata", id:7777},   {city:london,subject:"testdata", id:5555}]

tempArray1=[{city:london,subject:"testdata", id:8888},   {city:london,subject:"testdata", id:5555}]
     

im trying to get the result:

 newArray=[{city:london,subject:"testdata", id:5555}]

this is my try but i failed miserably

 let newArray=tempArray.map((x)=>{
                if (x.id== tempArray1.forEach((doc)=>{
                
                  return doc.id})) {return x
                  
                }
             
              }) 

CodePudding user response:

First:

If london is a string value, put it between Quotation marks.

Second:

Instead of using forEach you should use filter and some methods like below:

let newArray = tempArray.filter(x => tempArray1.some(doc => doc.id == x.id));
console.log(newArray)

The some method checks if any array elements pass a test (provided as a function).

The filter method creates a new array filled with elements that pass a test provided by a function.

You can check out the links: filter and some.

CodePudding user response:

You can use like below:

const filteredArray = tempArray.filter(obj1 => tempArray1.some(obj2 => obj1.id === obj2.id));
  • Related