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

Javascript 遍历数组并删除包含特定单词的所有值,javascript,Javascript,我有这个阵列: suggestions = [ "the dog", "the cat", "the boat", "boat engine", "boat motor", "motor oil" ]; 如何遍历数组并删除包含特定单词的所有条目 例如,删除包含单词“the”的所有实体,使数组变为: [ "

我有这个阵列:

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 correct=[],
len=建议长度,
i=0,
瓦尔;
对于(;i
使用ECMAScript 5的强大功能:

suggestions.reduce (
  function (r, s) {!(/\bthe\b/.test (s)) && r.push (s); return r; }, []);
尝试使用正则表达式

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);
    }
}
var建议=[“狗”,
“猫”,
“船”,
“船用发动机”,
“船用马达”,
“机油”
];
筛选的var=[],
len=建议长度,
瓦尔,
checkCondition=/\b\b/;
对于(变量i=0;i

我将使用以下设置:

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);
演示:

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

如果要生成包含匹配项的新数组,请正常循环,并将所有不匹配项推送到新数组。你可以用这个:

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);
var建议=[
“狗”,
“猫”,
“他当时去了”,
“船用发动机”,
“另一件事”,
“一些字符串什么的”
];
函数过滤器字(arr,过滤器){
变量i,j,cur,ret=[],
re=新的RegExp(“\\b”+过滤器+”\\b”);
对于(i=0,j=arr.length;i

演示:

向后循环,并使用正则表达式查找单词,然后
拼接
匹配的项目