代码之家  ›  专栏  ›  技术社区  ›  Elvira

检查数组元素是否包含其他数组中的部分值[重复]

  •  2
  • Elvira  · 技术社区  · 7 年前

    我想用两个数组做第三个数组。我想检查数组2是否包含数组1元素。

    所以Array2看起来像:

    ["Bol Sales ", "BookStore Amazon Sales", "Nintendo Sales", "XBOX" ]
    

    ["Bol", "Amazon","XBOX"]
    

    数组3应该是:

    ["Bol", "Amazon", "XBOX"]
    

    但大多数结果只有XBOX(因此,array1.val完全匹配array2.val)。

    我试过以下方法:

    var array1 = ["Bol", "Amazon", "XBOX"],
      array2 = ["Bol Sales ", "BookStore Amazon Sales", "Nintendo Sales", "XBOX"],
      array3 = [];
    
    
    array3 = array1.filter(function(store) {
      return array2.includes(store);
    });
    console.log(array3);
    
    array3 = array1.filter(function(store) {
      return array2.indexOf(store) >= 0;
    });
    console.log(array3);
    
    var storesToCheck = function(array1, array2) {
      return array1.some(function(value) {
        return array2.indexOf(value) >= 0;
      });
    };
    
    console.log(storesToCheck(array1, array2));
    1 回复  |  直到 7 年前
        1
  •  3
  •   Mihai Alexandru-Ionut    7 年前

    你可以用 includes some 通过一个 回拨 提供函数作为参数。

    arr2 = ["Bol Sales ", "BookStore Amazon Sales", "Nintendo Sales", "XBOX" ]
    arr1 =  ["Bol", "Amazon","XBOX"]
    
    console.log(arr1.filter(a => arr2.some(item => item.includes(a))));