Browsed several different questions/answers surrounding this question, but most rely on includes or indexOf
Problem: How any array to filter (names in this case). I need to filter it using 2 different arrays, one of which has startsWith criteria and the other has endsWith criteria
var names = ['BOB','CATHY','JAKOB','AARON','JUSTICE','BARBARA','DANIEL','BOBBY','JUSTINE','CADEN','URI','JAYDEN','JULIE']
startPatterns = ['BO','JU']
endPatterns = ['EN','ICE']
//res = ['BOB','JUSTICE','JUSTINE','JULIE','JAYDEN','JUSTICE']
Obviously you cannot do names.filter(d => d.startsWith(startPatterns)) because startPatterns is not a string but a array. Something like this isn't working and is terrible slow too:
res=[]
names.forEach(d => {
endPatterns.forEach(y => d.endsWith(y) ? res.push(d) : '')
startPatterns.forEach(s => d.startsWith(s) ? res.push(d) : '')})
console.log(res)
You can use Array.prototype.some on the pattern arrays to achieve this:
let filtered = names.filter(name => (
startPatterns.some(pattern => name.startsWith(pattern)) ||
endPatterns.some(pattern => name.endsWith(pattern))
))
The logic here being "Return true if the name begins with at least one of the start patterns OR ends with at least one of the end patterns".
You could build a regular expression and check the string against the pattern.
var names = ['BOB','CATHY','JAKOB','AARON','JUSTICE','BARBARA','DANIEL','BOBBY','JUSTINE','CADEN','URI','JAYDEN','JULIE'],
startPatterns = ['BO','JU'],
endPatterns = ['EN','ICE'],
regexp = new RegExp(`^(${startPatterns.join('|')})|(${endPatterns.join('|')})$`),
result = names.filter(s => regexp.test(s));
console.log(result);
A non regular expression approach with an array with the methods and wanted values.
var names = ['BOB','CATHY','JAKOB','AARON','JUSTICE','BARBARA','DANIEL','BOBBY','JUSTINE','CADEN','URI','JAYDEN','JULIE'],
patterns = [['startsWith', ['BO','JU']], ['endsWith', ['EN','ICE']]],
result = names.filter(s => patterns.some(([k, values]) => values.some(v => s[k](v))));
console.log(result);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With