简体   繁体   中英

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

Just for completeness, you could take a Set and compare with Set#has .

 let arr1 = [1, 2, 3, 4], arr2 = [1, 2], arr3 = [1, 5], base = new Set(arr1); console.log(arr2.every(Set.prototype.has, base)); console.log(arr3.every(Set.prototype.has, base)); 

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)); 

There is no need for loadash here just use native JavaScript Array#every method with Array#includes method

 function compareArray(arr1, arr2) { return arr2.every(v => arr1.includes(v)) } let arr1 = [1, 2, 3, 4] let arr2 = [1, 2] let arr3 = [1, 5] console.log(compareArray(arr1, arr2)) console.log(compareArray(arr1, arr3)) 

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

for(let x of arr2) {
    _.includes(arr1, x) || true;
}

You can use _.difference

 let arr1 = [1, 2, 3, 4] let arr2 = [1, 2] let arr3 = [1, 5] console.log(_.difference(arr2,arr1).length === 0) console.log(_.difference(arr3,arr1).length === 0) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script> 

You can use _.difference in such way:

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

const b = _.difference(arr2, arr1).length === 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM