Home > Software engineering >  How to compare two arrays of Json by each of their elements Id?
How to compare two arrays of Json by each of their elements Id?

Time:03-21

I have 2 arrays of objects with the same structure , each one of them came from database query. How can I 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}]
     

I am 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:

You can use like below:

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

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.

  • Related