[英]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? 我必须比较两个数组,如果只有数组1包含数组2的所有值,则返回true。对此合适的loadash函数是什么?
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 将arr1与arr2比较应返回true将arr1与arr3比较应返回false
You can just use every
: 您可以只使用
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 这里不需要loadash,只需将本机JavaScript
Array#every
方法与Array#includes
方法一起使用
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
您可以使用
_.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: 您可以通过
_.difference
方式使用_.difference
:
let arr1 = [1, 2, 3, 4]
let arr2 = [1, 2]
const b = _.difference(arr2, arr1).length === 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.