Quick actions

cmd+k|ctrl+k

Navigation

Languages

Return true if element exists in second array

Snippet info

Language

JavaScript

Visibility

public

Author

dhaval-90

Created

2022-01-30T23:37:39.634218Z

Updated

2022-01-31T00:03:30.854082Z

const array1 = ['a', 'b', 'c', 'x'];
const array2 = ['z', 'y', '1'];

function containsCommonItem2(arr1, arr2) {
  // loop through first array and create object where properties === items in the array
  // can we assume always 2 params?

  let map = {};
  for (let i=0; i < arr1.length; i++) {
    if(!map[arr1[i]]) {
      const item = arr1[i];
      map[item] = true;
    }
  }
  console.log(map);
  // loop through second array and check if item in second array exists on created object. 
  for (let j=0; j < arr2.length; j++) {
    if (map[arr2[j]]) {
      return true;
    }
  }
  return false
}

//console.log(containsCommonItem2(array1,array2));



//-------------------------------------------------------
//-------------------------------------------------------
function containsCommonItem3(arr1, arr2)
{
    return arr1.some(item => arr2.includes(item));    
}
console.log(containsCommonItem3(array1,array2));
INFO