0

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

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

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?
1

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?).

Comments

0
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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.