Intersection of 2 arrays with objects and arrays in object property

Asked

Viewed 140 times

0

Summarizing , I put in String format to illustrate here. I have an array as follows :

 "[{"cp_57b326e91ac094817aaf37f2":"1.Folha(Ponto)"}]"

And I also have the following object array

"[{"cp_57b326e91ac094817aaf37f2":["1.Folha(Ponto)","2.Relogio"]}]"

I would like to be able to do a function to check if the first array matches in some option of the second array. The keys are the same, but in the first array there will always be only one string as property, and in the second array, the object will have an array of strings.

In this example there is intersection, I tried to use Lodash using intersectionWith, but I couldn’t, I imagine because the second array has an array inside the obj.

1 answer

2

You can do it like this:

  • checks whether all array entries have objects whose keys have the value included in the corresponding array in the compared object.

const A = [{
  "cp_57b326e91ac094817aaf37f2": "1.Folha(Ponto)"
}];

const B = [{
  "cp_57b326e91ac094817aaf37f2": ["1.Folha(Ponto)", "2.Relogio"]
}];

const includes = (included, arr) => included.every(entry => {
  return Object.keys(entry).every(key => {
    return arr.find(obj => obj[key].includes(entry[key]));
  })
});

console.log(includes(A, B)); // true

Browser other questions tagged

You are not signed in. Login or sign up in order to post.