Search code examples
javascriptarrayslodash

Is there a loadash function to compare two arrays and return true only if all values from arr2 is present in arr1?


I have to compare two arrays and return true if only the array 1 contains all values of array 2. What is the suitable loadash function for this?

let arr1 = [1, 2, 3, 4]
let arr2 = [1, 2] 
let arr3 = [1, 5] 

comparing arr1 with arr2 should return true comparing arr1 with arr3 should return false


Solution

  • You can just use every:

    let arr1 = [1, 2, 3, 4];
    let arr2 = [1, 2];
    let arr3 = [1, 5];
    
    const allElements = (a1, a2) => a2.every(e => a1.includes(e));
    console.log(allElements(arr1, arr2));
    console.log(allElements(arr1, arr3));