0

In a health practice focused application I need to check whether one array is present inside another. Match conditions are: * It doesn't matter if there are additional non matching elements * It doesn't matter if a term appears more than once in the "haystack" array

We found a great solution in Lodash discussion. It is mocked up in JSFiddle and seems to work well.

But inside the rather complicated application it blows the browser apart using Lodash

Various configurations

This is the code that works with Lodash.

let haystack = ['health tips','iridology','something else','asdfasd'];
let needle = ['iridology','health tips'];

alert(_.intersection(needle,haystack).length === needle.length);

Does anyone know of a straightforward way of doing this in plain Javascript?

Cloudworks
  • 129
  • 7
  • You can import a single function from lodash without including the entire library in your code: `import intersection from 'lodash/intersection'` – Ori Drori Nov 01 '19 at 11:16

2 Answers2

0

You can do this by using Array.prototype.every on the needle array:

let haystack = ['health tips','iridology','something else','asdfasd'];
let needle = ['iridology','health tips'];


function checkArraySubset(innerArray, outerArray){
  return innerArray.every(str => outerArray.includes(str));
}
//true
console.log(checkArraySubset(needle, haystack));

needle = ['iridology','health tips', 'not present in haystack'];

//false
console.log(checkArraySubset(needle, haystack));

Make a set out of the haystack array if it is too long, that will result in an O(1) lookup:

let haystack = ['health tips','iridology','something else','asdfasd'];
let needle = ['iridology','health tips'];

function checkArraySubset(innerArray, outerArray){
   const lookup = new Set(outerArray);
   return innerArray.every(str => lookup.has(str));
}
//true
console.log(checkArraySubset(needle, haystack));
Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44
  • Also works fine and doesn't care about needle order (needle order doesn't matter but interesting). Useful commenting – Cloudworks Nov 01 '19 at 21:18
-2

One possible way using reduce and includes

let haystack = ['health tips','iridology','something else','asdfasd'];
let needle = ['iridology','health tips'];

const found = needle.reduce((acc, item) => acc && haystack.includes(item), true);


console.log('found ', found);
Tareq
  • 5,283
  • 2
  • 15
  • 18