Compare 2 two different arrays and show the object with the same value with js

Tags:



I need to find if values inside two different arrays of objects is equal. This is an example of what i need:

https://jsfiddle.net/5cb1xsq2/10/

I need to compare the object1 and object2 arrays, and show only the object1 array with the same ‘years’ value of the object2 array.

This is the result for this case:

{
    'name': 'john',
    'surname': 'doe',
    'years': 29
}

Thank you!

Answer

var array1 = [
  {
    name: "john",
    surname: "doe",
    years: 29,
  },
  {
    name: "tiler",
    surname: "phillis",
    years: 50,
  },
  {
    name: "mathias",
    surname: "terry",
    years: 45,
  },
];

var array2 = [
  {
    name: "mary",
    surname: "poppins",
    years: 32,
  },
  {
    name: "mickey",
    surname: "mouse",
    years: 29,
  },
  {
    name: "minnye",
    surname: "mouse",
    years: 36,
  },
];

var results = array1.filter(parentObj => array2.filter(childObj => childObj.years == parentObj.years).length > 0);


Source: stackoverflow