Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining whether one array contains the contents of another array in JavaScript/CoffeeScript

In JavaScript, how do I test that one array has the elements of another array?

arr1 = [1, 2, 3, 4, 5] [8, 1, 10, 2, 3, 4, 5, 9].function_name(arr1) # => true 
like image 660
Zeck Avatar asked Mar 20 '13 03:03

Zeck


People also ask

How do you check if an array contains a value from another array JavaScript?

JavaScript Array includes() The includes() method returns true if an array contains a specified value. The includes() method returns false if the value is not found.

How do I check if two arrays have the same contents?

The Arrays. equals() method checks the equality of the two arrays in terms of size, data, and order of elements. This method will accept the two arrays which need to be compared, and it returns the boolean result true if both the arrays are equal and false if the arrays are not equal.

How do you check if an array is subset of another array JS?

Naive Approach to Find whether an array is subset of another array. Use two loops: The outer loop picks all the elements of arr2[] one by one. The inner loop linearly searches for the element picked by the outer loop. If all elements are found then return 1, else return 0.


2 Answers

No set function does this, but you can simply do an ad-hoc array intersection and check the length.

[8, 1, 10, 2, 3, 4, 5, 9].filter(function (elem) {     return arr1.indexOf(elem) > -1; }).length == arr1.length 

A more efficient way to do this would be to use .every which will short circuit in falsy cases.

arr1.every(elem => arr2.indexOf(elem) > -1); 
like image 106
Explosion Pills Avatar answered Oct 09 '22 21:10

Explosion Pills


You can use array.indexOf():

pseudocode:

function arrayContainsAnotherArray(needle, haystack){   for(var i = 0; i < needle.length; i++){     if(haystack.indexOf(needle[i]) === -1)        return false;   }   return true; } 
like image 38
valentinas Avatar answered Oct 09 '22 20:10

valentinas