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
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.
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.
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.
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);
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With