So, I\'m using Jquery and have two arrays both with multiple values and I want to check whether all the values in the first array exist in the second.
Using array functions: [].filter and [].includes
Something like this:
[34, 78, 89].filter((v) => {
return [78, 67, 34, 99, 56, 89].includes(v);
});
This will return an array of the matches items
Then we can compare it with needles array
As a function it will be:
const contains = (haystack, needles) => {
return haystack.filter((v) => {
return needles.includes(v);
}).length === needles.length;
}
A one-liner to test that all of the elements in arr1
exist in arr2
...
With es6:
var containsAll = arr1.every(i => arr2.includes(i));
Without es6:
var containsAll = arr1.every(function (i) { return arr2.includes(i); });
If you need a little bit more visibility on which items are in the array you can use this one :
var tools = {
elem : {},
arrayContains : function(needles, arrhaystack) {
if (this.typeOf(needles) === 'array') {
needle.reduce(function(result,item,$i,array){ // You can use any other way right there.
var present = (arrhaystack.indexOf(item) > -1);
Object.defineProperty(tools.elem, item, {
value : present,
writable : true
});
},{})
return this.elem;
}
},
typeOf : function(obj) {
return {}.toString.call(obj).split(' ')[1].slice(0, -1).toLowerCase();
}
}
Use it with simply var check = tools.arrayContains([10,'foo'], [1,'foo','bar'])
Then you get the result like
10 : false
foo : true
Then if you need to get only one result if one of them is true you can :
arr = Object.values(check);
(arr.indexOf('true')) ? instru1 : instru2 ;
I don't think that's the better way but it's working & easily adaptable.
Considering this example I advise you to make an Object.create(tools)
before use it in your way.
You can use this simple function (renamed variables as per above answer for easy reading):
function contains(haystack, needles) {
return needles.map(function (needle) {
return haystack.indexOf(needle);
}).indexOf(-1) == -1;
}
Just for the fun of it, i've implemented something with Array.prototype.reduce() :
let areKeysPresent = function (sourceArray, referenceArray) {
return sourceArray.reduce((acc, current) => acc & referenceArray.includes(current), true)
}
You could take a Set and check all items agains it.
const
containsAll = (needles, haystack) =>
needles.every(Set.prototype.has, new Set(haystack));
console.log(containsAll([105, 112, 103], [106, 105, 103, 112]));