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

时间:2013-05-23 05:54:06

标签: javascript

我有这个数组:

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

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

例如,删除包含单词“the”的所有entires,因此数组变为:

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

4 个答案:

答案 0 :(得分:3)

创建新阵列可能更容易:

var correct = [],
    len = suggestions.length,
    i = 0,
    val;

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

答案 1 :(得分:1)

我会使用这个设置:

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);

DEMO: 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);

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

答案 2 :(得分:0)

尝试使用正则表达式

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);
    }
}

<强> check fiddle

答案 3 :(得分:-2)

使用ECMAScript5的强大功能:

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