[英]How can I compare two arrays with different length but they share the same values?
For Example:例如:
let array1 = [3, 1, 2, 5];
let array2 = [1, 2, 3];
How can I compare the both arrays to get my output a boolean value?如何比较两个数组以使我的输出成为布尔值?
If you want to check if one array is a subset of another array then you could try something like this:如果你想检查一个数组是否是另一个数组的子集,那么你可以尝试这样的事情:
let array1 = [3, 1, 2, 5]; let array2 = [1, 2, 3]; let isSubset = (arr1,arr2) => arr1.every(x=> arr2.includes(x)); console.log('Is array1 a subset of array2?',isSubset(array1,array2)); console.log('Is array2 a subset of array1?',isSubset(array2,array1));
Here first console.log
returns false because not all elements of array1
are present in array2
.这里首先
console.log
返回 false,因为并非array1
的所有元素都存在于array2
中。
But when we swap params inside isSubset
function we now check if all of the elements of array2
are present in array1
.但是当我们在
isSubset
函数中交换参数时,我们现在检查array2
的所有元素是否都存在于array1
中。 In this case we're getting true
state.在这种情况下,我们得到了
true
状态。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.