简体   繁体   English

如何比较两个长度不同但具有相同值的数组?

[英]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.

相关问题 如何在匹配键值的基础上比较两个不同长度和键的数组? - How can i compare two arrays of different length and keys on the basis of matching key values? 我如何排序☺我如何比较两个 arrays 并记录相同或不同的值 - how can I sort through an ☺how can i compare two arrays and log same or different values 使用lodash比较两个不同长度的数组 - Compare two different length arrays using lodash React JS:如何比较两个不同字段的值 - React JS : How can I compare values of two different fields 如何合并来自两个相同长度的不同数组的对象? - How to merge objects from two different arrays of same length? 在 JS 中比较两个长度相同但 object id 不同的 arrays - Compare two arrays with same length but having different object id's inside in JS 如果您不知道javascript中每个数组的长度,如何比较两个不同长度的数组? - how to compare two arrays of different length if you dont know the length of each one in javascript? 如何比较两个不同长度的对象数组? - How to compare 2 arrays of object with different length? 如何比较不同功能或相同功能的两个不同值? - How to compare two different values of different functions or same function? 我如何比较两个在javascript中没有相同长度的数组? - How can i Compare two Arrays, which don't have Same lenght in javascript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM