Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter array with multiple startsWith and endsWith arguments

Tags:

javascript

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)
like image 354
K.J.J.K Avatar asked Mar 19 '26 07:03

K.J.J.K


2 Answers

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".

like image 55
djfdev Avatar answered Mar 21 '26 20:03

djfdev


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);
like image 28
Nina Scholz Avatar answered Mar 21 '26 19:03

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!