1

Take the following arrays.

arrayOne = ["a", "b", "c", "d"];

arrayTwo = ["a", "b", "c", "d", "e", "f", "g"];

arrayThree = ["a", "b", "d", "g", "i"]

Assume I want to make sure that for every string in arrayOne, it is present in the other array I am matching it too.

Take a real life example, I want to make sure I have completed my shopping list, so I take out my shopping list and see that each item on my shopping list is present in the cart. There may be more items in my cart then in the shopping list, but as long as every item is there I am good.

Back to JavaScript, comparing arrayTwo against arrayOne returns true because a, b, c, and d are all present, while comparing arrayThree against arrayOne return false because c is not present.

I know this could be acomplished using a for loop with indexof, but is there a more elegant way to do it?

1
  • 5
    subset.every(x => set.includes(x)) Commented Apr 7, 2017 at 23:03

2 Answers 2

3

You can use Javascript array.prototype.every() method like this:

arrayOne = ["a", "b", "c", "d"];
arrayTwo = ["a", "b", "c", "d", "e", "f", "g"];
arrayThree = ["a", "b", "d", "g", "i"]

var containsAllElements = arrayOne.every(function(item) {
  return arrayTwo.indexOf(item) > -1;
});

console.log(containsAllElements);

Sign up to request clarification or add additional context in comments.

3 Comments

@AhmedMusallam yes we should always profit from JS predefined methods, note that we can optimize my code with includes() like suggested in comments.
yeah but includes needs a polyfill for IE :)
You have your arrays reversed. If you run your example, you get a false result. I mean it's a correct result if that's the desired test, but could be confusing for the OP since they're expecting the opposite.
0

try this:

arrayOne = ["a", "b", "c", "d"];
arrayTwo = ["a", "b", "c", "d", "e", "f", "g"];
arrayThree = ["a", "b", "d", "g", "i"]

Array.prototype.containsArray = function(arr){
  var result = true;
  var self = this;
  arr.forEach(function(item){
    if(self.indexOf(item) === -1){result = false}
  })
    return result;
}
arrayTwo.containsArray(arrayOne); // true
arrayThree.containsArray(arrayOne); // fasle

update: using Array.prototype.every: thanks to @chsdk

arrayOne = ["a", "b", "c", "d"];
arrayTwo = ["a", "b", "c", "d", "e", "f", "g"];
arrayThree = ["a", "b", "d", "g", "i"]
Array.prototype.containsArray = function(arr){
    var self = this;
    return arr.every(function(item){
       return self.indexOf(item) > -1;
    });
}
var one = arrayTwo.containsArray(arrayOne); // true
var two = arrayThree.containsArray(arrayOne); // fasle

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.