Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if array contains all elements of another array

I want a function that returns true if and only if a given array includes all the elements of a given "target" array. As follows.

const target = [ 1, 2, 3,    ]; const array1 = [ 1, 2, 3,    ]; // true const array2 = [ 1, 2, 3, 4, ]; // true const array3 = [ 1, 2,       ]; // false 

How can I accomplish the above result?

like image 938
lakshay bakshi Avatar asked Dec 04 '18 05:12

lakshay bakshi


People also ask

How do you check if an array contains all the elements of another array?

You can try with Array. prototype. every() : The every() method tests whether all elements in the array pass the test implemented by the provided function.

How do you check if an array has squared elements of another array?

Try sorting both arrays and iterating over both of them at the same, first squaring the number from the first array and then checking if it is equal to the element from the second array. Once you reach non-equal elements return false, otherwise return true.

How do you find an array within an array?

To access the elements of the inner arrays, you simply use two sets of square brackets. For example, pets[1][2] accesses the 3rd element of the array inside the 2nd element of the pets array.


2 Answers

You can combine the .every() and .includes() methods:

let array1 = [1,2,3],     array2 = [1,2,3,4],     array3 = [1,2];  let checker = (arr, target) => target.every(v => arr.includes(v));  console.log(checker(array2, array1));  // true console.log(checker(array3, array1));  // false
like image 99
Mohammad Usman Avatar answered Oct 12 '22 15:10

Mohammad Usman


The every() method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value. Stands to reason that if you call every() on the original array and supply to it a function that checks if every element in the original array is contained in another array, you will get your answer. As such:

const ar1 = ['a', 'b']; const ar2 = ['c', 'd', 'a', 'z', 'g', 'b'];  if(ar1.every(r => ar2.includes(r))){   console.log('Found all of', ar1, 'in', ar2); }else{   console.log('Did not find all of', ar1, 'in', ar2); }
like image 28
codemonkey Avatar answered Oct 12 '22 15:10

codemonkey