'How to compare two arrays of Json by each of their elements Id?
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
}
})
Solution 1:[1]
You can use like below:
const filteredArray = tempArray.filter(obj1 => tempArray1.some(obj2 => obj1.id === obj2.id));
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | mahooresorkh |
