I have 2 arrays of objects
var arr1 = [{id: "145", firstname: "dave", lastname: "jones"},
{id: "135", firstname: "mike",lastname: "williams"},
{id: "148", firstname: "bob",lastname: "michaels"}];
var arr2 = [{id: "146", firstname: "dave", lastname: "jones"},
{id: "135", firstname: "mike", lastname: "williams"},
{id: "148", firstname: "bob", lastname: "michaels"}];
I want to find the objects where the id exists in only one of the arrays and either log the object to the console or push the object to a new array.
Therefore I want to end up with
var arr1 = [{id: "145", firstname: "dave", lastname: "jones"}]
var arr2 = [{id: "146", firstname: "dave", lastname: "jones"}]
I tried using a forEach loop and splicing matching id's out of the array
arr1.forEach(function(element1, index1) {
let arr1Id = element1.id;
arr2.forEach(function(element2, index2) {
if (arr1Id === element2.id) {
arr1.splice(element1, index1)
arr2.splice(element2, index2)
};
});
});
console.log(arr1);
console.log(arr2);
But I ended up with
arr1
[ { id: '135', firstname: 'mike', lastname: 'williams' },
{ id: '148', firstname: 'bob', lastname: 'michaels' } ]
arr2
[ { id: '135', firstname: 'mike', lastname: 'williams' },
{ id: '148', firstname: 'bob', lastname: 'michaels' } ]
You could take a Set
for every array's id
and filter the other array by checking the existence.
var array1 = [{ id: "145", firstname: "dave", lastname: "jones" }, { id: "135", firstname: "mike", lastname: "williams" }, { id: "148", firstname: "bob", lastname: "michaels" }],
array2 = [{ id: "146", firstname: "dave", lastname: "jones" }, { id: "135", firstname: "mike", lastname: "williams" }, { id: "148", firstname: "bob", lastname: "michaels" }],
set1 = new Set(array1.map(({ id }) => id)),
set2 = new Set(array2.map(({ id }) => id)),
result1 = array1.filter(({ id }) => !set2.has(id)),
result2 = array2.filter(({ id }) => !set1.has(id));
console.log(result1);
console.log(result2);
.as-console-wrapper { max-height: 100% !important; top: 0; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With