Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Finding unmatched objects from 2 arrays

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' } ]
like image 991
DrumBongo Avatar asked Jan 02 '23 01:01

DrumBongo


1 Answers

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; }
like image 76
Nina Scholz Avatar answered Jan 08 '23 01:01

Nina Scholz