如何过滤出数组中不包含特定值的单词?

时间:2019-05-06 09:08:55

标签: javascript

我正在尝试制作此脚本,以便在其中可以将要过滤出array2的单词填入array1中。因此,我想获得一个仅包含array2中不包含来自array1的任何值的单词的新数组。

这就是我现在所拥有的,但是它不能正常工作,因为循环多次经过循环,最后每个单词都多次进入循环。现在我在array1中有3个值,每个单词将被检查3次,因此最后每个单词都将进入最终数组。我过滤出重复的单词到

有人对此有解决方案吗? JS小提琴链接:https://jsfiddle.net/45z1mpqo/

var array2 = ["January", "February", "March", "April", "May", "June"]
var array1 = ["uary", "May", "December"];
var notMatched = [];
let counter = 0;

for(var b = 0; b < array1.length; b++) {

    for(var i = 0; i < array2.length; i++) {

      if(array2[i].indexOf(array1[b]) != -1)
        { 
        //console.log(stringxa[i]);
        }
        else{
        notMatched[counter] = array2[i];
        counter++;
        }
    }
}
//this filter will remove duplicate elements from array
var unique = notMatched.filter(function(elem, index, self) {
    return index == self.indexOf(elem);
});
document.getElementById("text").innerHTML = unique;


<p id='text'>hi</p>

1 个答案:

答案 0 :(得分:1)

您可以在filter()上使用array2,并使用array1来检查字符串中是否包含some()的任何值

var array2 = ["January", "February", "March", "April", "May", "June"]
var array1 = ["uary", "May", "December"];


let res = array2.filter(x => array1.some(a => x.includes(a)));

console.log(res)