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

2 Answers 2

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.

answered Jul 9, 2022 at 15:45

2 Comments

A loop that just contains if ... ans.push is easily converted to filter.
guys can edit my answer if you want.
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)

answered Jul 9, 2022 at 16:14

1 Comment

I originally wrote the array incorrectly, I'm sorry

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.