遍历数组并删除包含特定单词的所有值

Iterate through an array and remove all values that contain a specific word

本文关键字:单词 数组 删除 包含特 遍历      更新时间:2023-09-26

我有这样一个数组:

suggestions = [ "the dog", 
                "the cat", 
                "the boat",
                "boat engine",
                "boat motor",
                "motor oil"
              ];

如何遍历数组并删除包含特定单词的所有条目?

例如,删除包含单词"the"的所有元素,使数组变为:

[ "boat engine",
  "boat motor",
  "motor oil"
];

创建一个新数组可能更容易:

var correct = [],
    len = suggestions.length,
    i = 0,
    val;
for (; i < len; ++i) {
    val = suggestions[i];
    if (val.indexOf('the') === -1) {
        correct.push(val);
    }
}

我将使用如下设置:

var suggestions = [
    "the dog",
    "the cat",
    "he went then",
    "boat engine",
    "another either thing",
    "some string the whatever"
];
function filterWord(arr, filter) {
    var i = arr.length, cur,
        re = new RegExp("''b" + filter + "''b");
    while (i--) {
        cur = arr[i];
        if (re.test(cur)) {
            arr.splice(i, 1);
        }
    }
}
filterWord(suggestions, "the");
console.log(suggestions);
演示:

http://jsfiddle.net/Kacju/

它向后循环,正确检查要查找的单词(通过使用'b标识符作为单词边界),并删除任何匹配。

如果您想生成一个包含匹配项的新数组,则正常循环并仅push任何不匹配项到新数组。你可以这样写:

var suggestions = [
    "the dog",
    "the cat",
    "he went then",
    "boat engine",
    "another either thing",
    "some string the whatever"
];
function filterWord(arr, filter) {
    var i, j, cur, ret = [],
        re = new RegExp("''b" + filter + "''b");
    for (i = 0, j = arr.length; i < j; i++) {
        cur = arr[i];
        if (!re.test(cur)) {
            ret.push(cur);
        }
    }
    return ret;
}
var newSuggestions = filterWord(suggestions, "the");
console.log(newSuggestions);
演示:

http://jsfiddle.net/Kacju/1/

尝试使用正则表达式

var suggestions = [ "the dog", 
                "the cat", 
                "the boat",
                "boat engine",
                "boat motor",
                "motor oil"
              ];
var filtered = [],
    len = suggestions.length,
    val,
    checkCondition = /'bthe'b/;
for (var i =0; i < len; ++i) {
    val = suggestions[i];
    if (!checkCondition.test(val)) {
        filtered.push(val);
    }
}

检查小提琴

使用ECMAScript5的功能:

suggestions.reduce (
  function (r, s) {!(/'bthe'b/.test (s)) && r.push (s); return r; }, []);