Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all strings from an array in another array [duplicate]

Tags:

javascript

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?

like image 554
Mihai Ciobanu Avatar asked Dec 24 '19 15:12

Mihai Ciobanu


2 Answers

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)
like image 116
StepUp Avatar answered Nov 02 '22 14:11

StepUp


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

first_array.reduce((ac, e) => ac && second_array.includes(e), true)
like image 23
Brandon Dyer Avatar answered Nov 02 '22 13:11

Brandon Dyer