如何通过允许部分匹配的字符串数组过滤字符串数组

时间:2018-11-06 12:06:48

标签: javascript arrays functional-programming

我在数组中有字符串,需要删除包含字符串的条目。而且还要删除部分匹配项。

var rawData = ["foo", "bar", "foobar", "barbaz", "boo" ]
var unwantedData = ["foo","baz"]
var cleanData = filter(rawData,unwantedData)
console.log(cleanData)
>>>["bar","boo"]

我当前的解决方案如下:

function filter(data,filterArray){
  return data.filter(rawEntry => {
    var t = true; // set to false if index is found
    filterArray.forEach(unwantedStr => { t = t && ~rawEntry.indexOf(unwantedStr) ? false : t });
    return t; //decides if entry gets removed by filter
  });
}

但是我觉得可能会有更好的方法。这在计算上可能不是最有效的方法。

3 个答案:

答案 0 :(得分:3)

除了使用Array#every,您还可以通过反逻辑并使用{​​{3}}来完成相同的操作。

var rawData = ["foo", "bar", "foobar", "barbaz", "boo"],
    unwantedData = ["foo", "baz"],
    result = rawData.filter(s => !unwantedData.some(t => s.includes(t)));

console.log(result);

答案 1 :(得分:2)

您可以使用.filter().every()方法.includes()

let rawData      = ["foo", "bar", "foobar", "barbaz", "boo"],    
    unwantedData = ["foo", "baz"];

let filterData = (a1, a2) => a1.filter(s => a2.every(v => !s.includes(v)));

console.log(filterData(rawData, unwantedData));

答案 2 :(得分:-1)

WORKFLOW_START_DATE = datetime(2018, 11, 5), 
WORKFLOW_SCHEDULE_INTERVAL = "50 18 * * *"

WORKFLOW_DEFAULT_ARGS = {
    'owner': 'admin',
    'depends_on_past': True,
    'start_date': WORKFLOW_START_DATE,
    'email': ['airflow@testing.com'],
    'email_on_failure': True,
    'email_on_retry': False,
    'retries': 1,
    'retry_delay': timedelta(minutes=5)
}

t1 = BashOperator(
    task_id='download',
    bash_command='-c "test_download.sh {{ execution_date.strftime("%d-%b-%Y") }}"',
    dag=dag)