简体   繁体   中英

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 .
But when we swap params inside isSubset function we now check if all of the elements of array2 are present in array1 . In this case we're getting true state.

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