5

Given an array of strings:

const first_array = ['aaa', 'bbb', 'ccc']

and another array of strings:

const second_array = ['aaa', 'bbb', 'ccc', 'ddd', 'eee']

How can I return true if all the strings from first_array are present in the second_array and false otherwise?

hindmost
  • 7,026
  • 3
  • 25
  • 37
  • 5
    Does this answer your question? [Check if an array is subset of another array](https://stackoverflow.com/questions/38811421/check-if-an-array-is-subset-of-another-array) – Alexander Vidaurre Arroyo Dec 24 '19 at 15:18
  • If you use Lodash/Underscore, also take a look at [`_.difference`](https://lodash.com/docs/4.17.15#difference) – hindmost Dec 24 '19 at 15:27

2 Answers2

10

You can use every() method to check whether every element is contained in second_array:

const result = first_array.every(f => second_array.includes(f))

An example:

const first_array = ['aaa', 'bbb', 'ccc']
const second_array = ['aaa', 'bbb', 'ccc', 'ddd', 'eee']

const result = first_array.every(f => second_array.includes(f))
console.log(result)
StepUp
  • 30,747
  • 12
  • 76
  • 133
1

This should be a nice one-liner to solve the problem.

first_array.reduce((ac, e) => ac && second_array.includes(e), true)
Brandon Dyer
  • 1,232
  • 12
  • 21