首页 > 解决方案 > 如何根据另一个数组中的单词过滤数组?

问题描述

我想过滤包含在数组中的一些单词,包含在字符串中。例如:

输入

1.“消失”定义:

[ "Cease to be visible.",
  "Cease to exist or be in use.",
  "Be lost or go missing, become IMPOSSIBLE to find.",
  "Abduct or arrest and kill or detain (a person) for political reasons,
  without making their fate known." ]

2.违禁词:

[ 'without', 'impossible' ]

结果

[ "Cease to be visible.", "Cease to exist or be in use." ]

我想,我非常接近答案:

function filterDefinition (defs, badWords) {
  const definitionFilter = defs.filter(function(def) {
    if (def.includes(badWords || badWords.toUpperCase()) {
      return !defs
    }
  });
  return definitionFilter;
}

标签: javascriptfilterword

解决方案


像这样?

function filterDefinition (defs, badWords) {
  return defs.filter(function(def) {
    return !badWords.some(badWord => def.includes(badWord) || def.includes(badWord.toUpperCase()));
  });
}

String.includes(string) 不适用于数组。


推荐阅读