Home > Net >  How to check if an array of strings contains all elements of the array?
How to check if an array of strings contains all elements of the array?

Time:07-10

I have an array of strings array1 , and array2 to compare. How to check for the occurrence of all elements in strict accordance and create a new array. I understand that in my case it is necessary to apply filter includes. I have seen the answer for string.

An example of what is required in my case and the expected result:

array1 [ 'apple_mango_banana', 'mango_apple_banana', 'apple_banana' ]
array2 [ 'apple', 'mango' ]

result ['apple_mango_banana', 'mango_apple_banana' ]

CodePudding user response:

const array1 = [ 'apple_mango_banana', 'mango_apple_banana', 'apple_banana' ]
const array2 = [ 'apple', 'mango' ]

const goal = [ 'apple_mango_banana', 'mango_apple_banana' ]

let result = array1.filter(item1 => array2.every(item2 => item1.includes(item2)))

console.log(result)

CodePudding user response:

You said array of strings but your code looks like an array of arrays of strings. Assumining it's the latter, do you do it like this:

let array = [['apple', 'mango', 'banana'], ['mango', 'apple', 'banana'], ['apple', 'banana']]
let comp = ['apple', 'mango']
let ans = []

for (el of array) {
    if (comp.every(y => el.includes(y))) {
        ans.push(el)
    }
}

console.log(ans)

I'm sure you can find a one-liner but this way works.

  • Related