0

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' ]
Alex
  • 101
  • 7
  • What have you tried? I would suggest using loops before you go for the one-line-solution – Michael Jul 09 '22 at 15:30
  • i tried applying the filter using this example var is Every = arr.every(item => str.includes(item)); – Alex Jul 09 '22 at 15:37
  • Please add quotes around strings and commas between array elements, so we can see what you're really trying to compare. – Barmar Jul 09 '22 at 15:47
  • array1 [['apple_mango_banana'], ['mango_apple_banana'], ['apple_banana']] array2 ['apple', 'mango'] – Alex Jul 09 '22 at 16:02

2 Answers2

1

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.

Lian
  • 2,197
  • 2
  • 15
  • 16
0

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)
lukas.j
  • 6,453
  • 2
  • 5
  • 24