-1

i want to do something like this,

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

output should be like

{obj1}

salman
  • 55
  • 6
  • 2
    Does this answer your question? [How to determine equality for two JavaScript objects?](https://stackoverflow.com/questions/201183/how-to-determine-equality-for-two-javascript-objects) – icecub Sep 09 '21 at 16:18
  • You should also check this one - https://www.codegrepper.com/code-examples/javascript/javascript+compare+two+arrays+of+objects – Rajeev Singh Sep 15 '21 at 10:42

4 Answers4

1

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);
Doron Mor
  • 71
  • 9
0

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});
rustyBucketBay
  • 4,320
  • 3
  • 17
  • 47
0
Salik Khan
  • 119
  • 6
0

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.

James Lin
  • 162
  • 3
  • 18
  • Your solution will not work properly. take the following example: `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 = [{a: 'foo1', b: 'bar1'}, obj2, obj3] let array2 = [{a: 'foo1', b: 'bar1'}, obj4, obj5] let result = array1.filter(o1 => array2.some(o2 => o1 === o2)); console.log(result);` – Doron Mor Sep 09 '21 at 16:41
  • I just updated my answer regarding an object deep comparison. You can use an object deep comparison method instead of `o1 === o2`. – James Lin Sep 09 '21 at 16:51