E
E
Eugene Chefranov2020-04-27 10:23:10
JavaScript
Eugene Chefranov, 2020-04-27 10:23:10

How to compare two arrays and find occurrences?

There are two arrays with objects

var four = [{
    "n1": 2,
    "n2": 4,
    "n3": 15,
    "n4": 23
},
{
    "n1": 15,
    "n2": 4,
    "n3": 23,
    "n4": 3
},
{
    "n1": 4,
    "n2": 9,
    "n3": 7,
    "n4": 3
}]

var three = [{
    "m1": 2,
    "m2": 6,
    "m3": 9
},
{
    "m1": 15,
    "m2": 4,
    "m3": 23
},
{
    "m1": 1,
    "m2": 3,
    "m3": 2
},
{
    "m1": 9,
    "m2": 4,
    "m3": 3
}]

It is necessary to compare the three array with the four array and if there is a match of three (no more, no less) values ​​of the object, then output this object with 4 values.
According to the example above, when compared, it should output:
2,6,9 - нет вхождений
15,4,23 - входит в / 2, 4, 15, 23 / 15, 4, 23, 3 /
1,3,2 - нет вхождений
9,4,3 - входит в / 4,9,7,3 /

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2020-04-27
@Chefranov

const fourValues = four.map(Object.values);

const result = three.map(n => {
  const values = Object.values(n);
  const intersections = fourValues.filter(m => values.every(v => m.includes(v)));
  return `${values} - ${intersections.length
    ? `входит в / ${intersections.map(m => `${m}`).join(' / ')} /`
    : 'нет вхождений'}`;
});

T
twobomb, 2020-04-27
@twobomb

var result = four.filter(v=>three.some(v1=> Object.values(v1).filter(v2=>Object.values(v).includes(v2)).length == 3  ),[]);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question