Home > Net >  how to check for same objects in two different arrays in JavaScript
how to check for same objects in two different arrays in JavaScript

Time:09-17

i want to do something like this,

let array1 = [{obj1}, {obj2},{obj3}] 
let array2 = [{obj1}, {obj4},{obj5}]

output should be like

{obj1}

CodePudding user response:

This could work for simple objects.

Take in mind that it will not work for functions based properties.

const array1 = [{a:1}, {b:2},{c:3}] 
const array2 = [{a:1}, {d:4},{e:5}]

const array1Stringify = array1.map(el => JSON.stringify(el));
const array2Stringify = array2.map(el => JSON.stringify(el));

const result = array1Stringify.filter(el => array2Stringify.includes(el)).map(el => JSON.parse(el));

console.log(result);

CodePudding user response:

As commented, most of your problem is to define how your objects equality will be evaluated. Once you get that resolved, simply checking for the matches of one array in the other shold give you the matches you are after. Most readable and naive way, with a double for.

let array1 = ['hello', 'world', 'I rule'] 
let array2 = ['hello', 'whatever', 'hey brother']

let matches = [];
for (let i = 0; i < array1.length; i  ) {
    for (let j = 0; j < array2.length; j  ) {
        if (array1[i] === array2[j]) { //equality for object problem here
            matches.push(array1[i]);
        }
    }
}

console.log({matches});

CodePudding user response:

CodePudding user response:

Is there any specific reason for wrapping with curly brackets? Here is a solution for you. Hopefully, this answer may be helpful for your question.

const obj1 = {a: 'foo1', b: 'bar1'};
const obj2 = {a: 'foo2', b: 'bar2'};
const obj3 = {a: 'foo3', b: 'bar3'};
const obj4 = {a: 'foo4', b: 'bar4'};
const obj5 = {a: 'foo5', b: 'bar5'};

let array1 = [obj1, obj2, obj3] 
let array2 = [obj1, obj4, obj5]

let result = array1.filter(o1 => array2.some(o2 => o1 === o2));

console.log(result);

If you want an object deep comparison for each object, then please visit this solution for that.

  • Related