如何从不包含搜索关键字的字符串数组中删除字符串?

时间:2018-06-05 10:47:34

标签: javascript arrays

我有一个字符串数组(testArray)。我需要从数组中删除不包含至少一个searchTerms的字符串。testArray应该忽略searchTerms的情况。

编辑:结果数组应该包含字符串,即使搜索字词是字符串中单词的一部分。

例如:"someright text"应包含在结果中。



var testArray = [
    "I am",
    "I am wrong and I don't know",
    "I am right and I know",
    "I don't know",
    "some text",
    "I do know"
  ],
  searchTerms = ["I", "right","know"] //or ["i", "right","know"];

$.each(searchTerms, function(index, term) {
  var regX = new RegExp(term, "i");
  testArray = $.map(testArray, function(item) {
    if (regX.test(item)) {
      return item;
    } else {
      return;
    }
  });
});

console.log(testArray);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

结果应如下所示,

testArray = [
        "I am",
        "I am wrong and I don't know",
        "I am right and I know",
        "I don't know",           
        "I do know"
      ]

2 个答案:

答案 0 :(得分:3)

使用Array.filterArray.someArray.includes

var testArray = ["I am", "I am wrong and I don't know", "I am right and I know", "I don't know", "some text", "I do know"],
searchTerms = ["I", "right","know"];

searchTerms = searchTerms.map(w => w.toLowerCase());

/* Use filter to filter only those records which have the search term in it. */
var result = testArray.filter((s) => s.split(" ").some((w) => searchTerms.includes(w.toLowerCase())));

console.log(result);

修改

var testArray = ["I am", "I am wrong and I don't know", "I am right and I know", "I don't know", "some text", "I do know", "someright"],
searchTerms = ["I", "right","know"];

searchTerms = searchTerms.map(w => w.toLowerCase());

/* Use filter to filter only those records which have the search term in it. */
var result = testArray.filter((s) => searchTerms.some(w => s.toLowerCase().includes(w)));

console.log(result);

答案 1 :(得分:0)

以下是代码在注释中调整代码的情况,getter只返回数组中的值而不是值的属性。

testArray = [
  "I am",
  "I am wrong and I don't know",
  "I am right and I know",
  "I don't know",           
  "I do know"
];
const filterFn = getter => comparer => o =>
  comparer(getter(o));

//you are not getting a property of an object item in the array but the value
const getValue = o => o;

// compare search contains word
const containsWord = search => {
  //small optimization
  const searchAsRegExp = search.map(s=>new RegExp(s,"i"));
  return value =>
    searchAsRegExp.some(reg=>reg.test(value));
};

console.log(
  `using containsWord(["I", "right","know"])`,
  testArray.filter(filterFn(getValue)(containsWord(["I", "right","know"])))
)