• Home
  • Jobs
  • Courses
  • Questions
  • Teachers
  • For business
  • ES/EN

0

29
Views
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?

about 1 month ago ·

Juan Pablo Isaza

1 answers
Answer question

0

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.

about 1 month ago · Juan Pablo Isaza Report
Answer question
Find remote jobs
Loading

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2022 PeakU Inc. All Rights Reserved.