var arr1 = [
"T-1",
"CAT"
]
var arr2 = [
"Lemuel F (T-1)",
"Levi C (T-1)",
"Monfel (T-2)",
"JC (T-1)",
"Wrecker (CAT)"
]
const arr3 = arr2.filter(a => {
return (a.includes(arr1[0]));
});
console.log("arr3", arr3);
This is the output I get :
[ 'Lemuel F (T-1)', 'Levi C (T-1)', 'JC (T-1)' ]
This is the output I'm trying to get
[ 'Lemuel F (T-1)', 'Levi C (T-1)', 'JC (T-1)','Wrecker (CAT)' ]
I'm trying to use multiple includes but I still cant find a way. I've tried this syntax
return (a.includes(arr1[0]) && (a.includes(arr1[1]
CodePudding user response:
Answering your question here is how to use include in your situation, however I also recommend using regex, since it simplifies the issue quite a bit and only requires you to iterate over each element once.
const arr1 = ["T-1", "CAT"];
const arr2 = [
"Lemuel F (T-1)",
"Levi C (T-1)",
"Monfel (T-2)",
"JC (T-1)",
"Wrecker (CAT)"
];
// using includes
const arr3 = arr2.filter((value2) => arr1.some((value1) => value2.includes(value1)));
console.log(arr3);
// using regex
const regex = new RegExp(arr1.join("|"), "g");
const arr4 = arr2.filter((value) => value.match(regex));
console.log(arr4);
CodePudding user response:
A quick solution that can be used for your case is to have a Regular Expression that tests for the existence of the substrings inside the sentences array.
const subStrings = ["T-1", "CAT"],
strings = ["Lemuel F (T-1)", "Levi C (T-1)", "Monfel (T-2)", "JC (T-1)", "Wrecker (CAT)"],
/**
* create a RegExp object on the fly
* the "|" token acts like the logical OR operator
* basically we'll have this regex: "T-1|CAT"
*/
regExp = new RegExp(subStrings.join('|')),
res = strings.filter(s => regExp.test(s));
console.log(res);
CodePudding user response:
You're basically looking at an array intersection (arr1
× arr2
), but with some slightly tweaked logic as you want the predicate to look at the string inside the parenthesis in arr2
. You can use regex to extract the keyword you want to match (that is encapsulated between parenthesis), and check if it exists in arr1
:
arr2.filter(entry => {
const keyword = entry.match(/\(([^)] )\)/)[1];
return arr1.includes(keyword);
});
Here is a proof-of-concept example based on your code, which returns the data as you expect:
const arr1 = ["T-1", "CAT"];
const arr2 = [
"Lemuel F (T-1)",
"Levi C (T-1)",
"Monfel (T-2)",
"JC (T-1)",
"Wrecker (CAT)",
];
const arr3 = arr2.filter(entry => arr1.includes(entry.match(/\(([^)] )\)/)[1]));
console.log(arr3);
CodePudding user response:
const arr3 = arr2.filter(item=>arr1.some(item2=>item2.includes(item)))