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' ]
-
What have you tried? I would suggest using loops before you go for the one-line-solutionMichael– Michael2022年07月09日 15:30:55 +00:00Commented Jul 9, 2022 at 15:30
-
i tried applying the filter using this example var is Every = arr.every(item => str.includes(item));Alex– Alex2022年07月09日 15:37:27 +00:00Commented 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.Barmar– Barmar2022年07月09日 15:47:34 +00:00Commented Jul 9, 2022 at 15:47
-
array1 [['apple_mango_banana'], ['mango_apple_banana'], ['apple_banana']] array2 ['apple', 'mango']Alex– Alex2022年07月09日 16:02:57 +00:00Commented Jul 9, 2022 at 16:02
2 Answers 2
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
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
Alex
I originally wrote the array incorrectly, I'm sorry
lang-js