I'd personally use the Array.every()
method (though this is, of course, dependent upon a browser that implements this method) in conjunction with Array.indexOf()
, which would result in something akin to the following:
var contains = function(needle, haystack){
return needle.every(function(a){
return haystack.indexOf(a) > -1;
});
};
Combining that with the approach you've already produced (testing for browser-support):
var contains = function(needle, haystack){
if ([].every){
return needle.every(function(a){
return haystack.indexOf(a) > -1;
});
}
else {
var result = true;
for (var i = 0, len = needle.length; i < len; i++){
if (haystack.indexOf(needle[i]) === -1) {
return false;
}
}
return result;
}
}
var a1 = [1,2,3],
a2 = [1,2,3,4];
console.log(contains(a1, a2));
JS Fiddle demo.
Note that the else
code isn't optimised, it's simply there to demonstrate the code. Having said that, there is a shim for Array.every()
at the MDN page (in the references, below) that might make things easier.
References: