过滤具有多个startsWith和endsWith参数的数组

时间:2019-12-13 20:06:48

标签: javascript

浏览了围绕此问题的几个不同的问题/答案,但大多数都依赖于includesindexOf

问题:如何过滤任何数组(在这种情况下为names)。我需要使用2个不同的数组对其进行过滤,其中一个具有startsWith条条件,另一个具有endsWith条条件

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']

很显然,您无法执行names.filter(d => d.startsWith(startPatterns)),因为startPatterns不是字符串而是数组。像这样的东西行不通,而且速度太慢了:

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)

2 个答案:

答案 0 :(得分:6)

您可以在模式数组上使用Array.prototype.some来实现此目的:

let filtered = names.filter(name => (
  startPatterns.some(pattern => name.startsWith(pattern)) ||
  endPatterns.some(pattern => name.endsWith(pattern))
))

这里的逻辑是“如果名称以至少一种起始模式开头或至少以一种结束模式返回,则返回true

答案 1 :(得分:3)

您可以构建一个正则表达式,并根据模式检查字符串。

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);

一种非正则表达式方法,其中包含具有方法和所需值的数组。

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);