Compare array of objects with array

Viewed 36

I have an array of objects:

arr1 = [
        {
            "id": 1,
            "color": "blue",
            "label": "School",
        },
        {
            "id": 2,
            "color": "red",
            "label": "Work",
        }
    ]

and a simple array:

arr2 = [ 2, 5 ]

I want to write a method that returns true if one of the object ids from arr1 can be found in arr2. So I could use it with

v-if

later. What's your suggestion?

1 Answers
let arr1 = [
  {
      "id": 1,
      "color": "blue",
      "label": "School",
  },
  {
      "id": 2,
      "color": "red",
      "label": "Work",
  }
]

let arr2 = [ 2, 5 ]

let arr1_id = arr1.map(function (obj) {
  return obj.id;
});

function check(array1, array2) {
  let intersection = array1.filter(element => array2.includes(element));
  if (intersection.length > 0) {
    return true
  }
  else {return false}
}

bool = check(arr1_id,arr2)
console.log(bool)
Related