0

I have found some solutions on this site and others such as Array.prototype.includes() and Array.prototype.indexOf() and jQuery.inArray().

Each of these solutions are well suited to check if a single value 'x' is in array ['x','y','z'].

My question is: How can I test to see if multiple values are present in an array. In other words, is array X in array Y?

For example:

Is ['a','e','f'] in ['a','b','c','d','e','f','g']? Result: True.

Is ['a','e','z'] in ['a','b','c','d','e','f','g']? Result: False.

EDIT: Ideally the solution would work as far back as IE 10.

WillD
  • 5,170
  • 6
  • 27
  • 56

2 Answers2

2

This is fairly concise and does what you want:

const array1 = ['a','b','c','d','e','f','g'];
const array2 = ['a','e','f'];
console.log(array2.every(currentValue => array1.includes(currentValue)));
danday74
  • 52,471
  • 49
  • 232
  • 283
  • Can you see of a version of this working that would use `.indexof()` instead of `.includes()` I ask because it looks like .includes() doesn't work in Internet Explorer – WillD Sep 21 '18 at 22:44
1

Everything after the first 3 lines is just for testing and to show how to use this function. One case is true the other is false.

Array.prototype.containsAll = function(values) {
  return values.every((val) => this.indexOf(val) !== -1);
}

var array = ['a','b','c','d','e','f','g'];
var testA = ['a', 'e', 'f'];
var testB = ['a', 'e', 'z'];
var testC = ['x', 'a'];

var res = array.containsAll(testA);
console.log(res);

var res = array.containsAll(testB);
console.log(res);

var res = array.containsAll(testC);
console.log(res);

Added a function to the Array Prototype which is handling your problem.

sascha10000
  • 1,245
  • 1
  • 10
  • 22
  • Can you see of a version of this working that would use `.indexof()` instead of `.includes()` I ask because it looks like .includes() doesn't work in Internet Explorer – WillD Sep 21 '18 at 22:44
  • Yes I modified the example. But you should have easily figured that out yourself. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf – sascha10000 Sep 21 '18 at 23:58