Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Is there an easy way of knowing if and array contains all elements of another array?

Example:

var myarray = [1,2,3];
var searchinarray = [1,2,3,4,5];

searchinarray contains all elements of myarray, so this should return true.

Regards

share|improve this question

3 Answers 3

up vote 1 down vote accepted

A contains function should only visit members of the array to be contained that exist, e.g.

var myArray = [1,,2];
var searchInArray = [1,2,3];

contains(myArray, searchInArray);

should return true, however a simple looping solution will return false as myArray[1] doesn't exist so will return undefined, which is not present in the searchInArray. To easily avoid that and not use a hasOwnProperty test, you can use the Array every method:

function contains(searchIn, array) {
  return array.every(function(v){return this.indexOf(v) != -1}, searchIn);
}

so that:

var a = [1,,3];
var s = [1,2,3,4,5];

console.log(contains(s, a));  // true

You can add a contains method to all instances of Array if you wish:

if (typeof Array.prototype.contains == 'undefined') {
  Array.prototype.contains = function(a) {
    return a.every(function(v, i) {
      return this.indexOf(v) != -1;
    }, this);
  }
}

console.log(s.contains(a));      // true
console.log(s.contains([1,9]));  // false

You may need a polyfill for browsers that don't have .every (IE 8?).

share|improve this answer

Here is an implementation of that function:

function contains(a, s) {
   for(var i = 0, l = s.length; i < l; i++) {
      if(!~a.indexOf(s[i])) {
         return false;
      }
   }
   return true;
}

This shows that it does what you describe:

> var myarray = [1,2,3];
> var searchinarray = [1,2,3,4,5];
> contains(myarray, searchinarray)
false
> contains(myarray, [1,2])
true
> contains(myarray, [2,3])
true
share|improve this answer
    
This should test that s[i] actually exists, or use a method like forEach that only visits members of s that exist. e.g. should contains(s, [,,1]) return true or false? –  RobG Oct 9 '14 at 6:12
function compare(array, contains_array) {
 for(var i = 0; i < array.length; i++) {
  if(contains_array.indexOf(array[i]) == -1) return false;
 }
 return true;
}

compare(myarray, searchinarray);
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.