检查数组包含另一个数组的每个元素

时间:2019-12-03 15:16:45

标签: javascript

我如何将一个数组的每个元素检入另一个数组?这里的array2包含array1的每个元素。

代码:

function find(a, b) {
     var ai=0, bi=0;
  var result = [];

  while( ai < a.length && bi < b.length )
  {
     if      (a[ai] < b[bi] ){ ai++; }
     else if (a[ai] > b[bi] ){ bi++; }
     else /* they're equal */
     {
       result.push(a[ai]);
       ai++;
       bi++;
     }
  }

  if(JSON.stringify(a)==JSON.stringify(result)){
    return true;
  }else if(JSON.stringify(b)==JSON.stringify(result)){
    return true;
  }else{
    return false;
  }
  // return result;

}

var array1 =  ["Area", "Code", "Date", "Invoice Amt", "Invoice No", "Party Address", "Party Name", "Pincode"];
var array2 = ["Area", "Code", "Date", "Invoice Amt", "Invoice No", "Name", "Party Address ", "Party Name", "Pincode"];

console.log(find(array1, array2)); //returns false
console.log(find(array2, array1)); // return false

4 个答案:

答案 0 :(得分:2)

如果要一个一个地检查每个值,可以使用mapincludes来检查数组是否包含array1中的任何值

var array1 = ["Area", "Code", "Date", "Invoice Amt", "Invoice No", "Party Address", "Party Name", "Pincode"];
var array2 = ["Area", "Code", "Date", "Invoice Amt", "Invoice No", "Name", "Party Address ", "Party Name", "Pincode"];

array1.map(x => console.log(array2.includes(x)))

答案 1 :(得分:2)

字符串的末尾包含空格,因此请确保在处理字符串之前先trim

例如:派对地址包含空格

function isSuperset(set, subset) {
    for (var elem of subset) {
        if (!set.has(elem)) {
            return false;
        }
    }
    return true;
}


var array1 =  new Set(["Area", "Code", "Date", "Invoice Amt", "Invoice No", "Party Address", "Party Name", "Pincode"].map(el => el.trim()));
var array2 = new Set(["Area", "Code", "Date", "Invoice Amt", "Invoice No", "Name", "Party Address ", "Party Name", "Pincode"].map(el => el.trim()));

let result = isSuperset(array2, array1);
console.log(result);

答案 2 :(得分:0)

您可以使用Array.prototype.includes()

const arr1 = [/* someValues */];
const arr2 = [/* someMoreValues */];

for (let value of arr1) {
    if (arr2.includes(value)) {
        // do stuff
    }
}

您还可以将includes()map()一起使用

arr1.map(x => console.log(arr2.includes(x)));

答案 3 :(得分:0)

我真的不喜欢在接受的答案中建议使用for...循环,尽管它比map()解决方案具有主要优势,因为它在击中丢失元素时具有捷径。

尽管如此,recipe还是有一个高阶:

const isSubset = (set, subset) => subset.every(item => set.includes(item))

您可以在以下实时代码段中进行查看:

const   arr1 = ["Area", "Code", "Date", "Invoice Amt", "Invoice No", "Party Address", "Party Name", "Pincode"],
        arr2 = ["Area", "Code", "Date", "Invoice Amt", "Invoice No", "Name", "Party Address ", "Party Name", "Pincode"],
        arr3 = [...'abc'],
        arr4 = [...'abcd']
        
const isSubset = (set, subset) => subset.every(item => set.includes(item))
        
console.log(isSubset(arr1,arr2))  //false
console.log(isSubset(arr2,arr1))  //false
console.log(isSubset(arr3,arr4))  //false
console.log(isSubset(arr4,arr3))  //true
.as-console-wrapper{min-height:100%}