0

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!

runnerDev
  • 49
  • 4
  • Does this answer your question? [Comparing Arrays of Objects in JavaScript](https://stackoverflow.com/questions/27030/comparing-arrays-of-objects-in-javascript) – Kinglish Jun 06 '21 at 19:53
  • Please include the relevant data samples in the question and importantly show what you have tried. Demo links are great but only as support for what actually exists in the question itself. We shouldn't have to go off site just to do n initial review of your issue – charlietfl Jun 06 '21 at 19:53
  • What have you tried? There are many examples of this on Stack Exchange, have you searched how to filter one array of objects by another? – Kinglish Jun 06 '21 at 19:57

3 Answers3

2

If there is only one match, then something like this?

let result;
for (let i = 0; i < array2.length; i += 1) {
  const a2 = array2[i]
  const index = array1.findIndex((a1) => a1.years === a2.years);
  if (index > -1) {
    result = array1[index];
    break;
  }
}
Steve Bunting
  • 419
  • 5
  • 12
2
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);
Paul Braganza
  • 111
  • 1
  • 6
1

You can filter the first array using the result of filtering the second array with each element comparison.

var array1 = [
  { years: 29 },
  { years: 50 },
  { years: 60 }
];

var array2 = [
  { years: 29 },
  { years: 30 },
  { years: 50 }
];

console.log(array1.filter(x => array2.filter(y => y.years == x.years).length > 0));
MarioZ
  • 981
  • 7
  • 16