从 javascript 文件调用时,函数不会在剃刀页面上执行

我有两个 JS 数组。他们是arr1和arr2。我想创建另一个名为arr3. 现在它想要比较arr1并插入所有包含和不包含的arr2元素。arr2arr1


例子:


arr1:


  0:

    des: "cont1"

    note: "cont1"

    pro_code: "XXY"

  1:

    des: "cont2"

    note: "cont2"

    pro_code: "NNB"

  2:

    des: "cont4"

    note: "cont4"

    pro_code: "QQA"

  3:

    des: "cont5"

    note: "cont5"

    pro_code: "GFD"

arr2:


  0:

    des: "cont1"

    note: "cont1"

    pro_code: "XXY"

  1:

    des: "cont2"

    note: "cont2"

    pro_code: "NNB"

  2:

    des: "cont3"

    note: "cont3"

    pro_code: "QAS"

在arr2包含pro_code: QAS. 但它不在arr1。所以它应该包含在arr3.


在arr1包含arr1[4] pro_code: GFD. 它should not包含在arr3. Becaseaar1可以包含其他元素。


Herearr2必须包含 中的元素arr1。中不能有附加元素arr2。


预期输出:


const arr3 = [{

  des: "cont3",

  note: "cont3",

  pro_code: "QAS"

}

我试过的代码,不起作用。请帮我解决这个问题。


摇曳的蔷薇
浏览 142回答 3
3回答

慕哥9229398

Set您可以对所有值取 apro_code并通过检查该值是否不在集合中来过滤第二个数组。const    array1 = [{ des: "cont1", note: "cont1", pro_code: "XXY" }, { des: "cont2", note: "cont2", pro_code: "NNB" }, { des: "cont4", note: "cont4", pro_code: "QQA" }, { des: "cont5", note: "cont5", pro_code: "GFD" }],    array2 = [{ des: "cont1", note: "cont1", pro_code: "XXY" }, { des: "cont2", note: "cont2", pro_code: "NNB" }, { des: "cont3", note: "cont3", pro_code: "QAS" }],    pro_codes = new Set(array1.map(({ pro_code }) => pro_code)),    result = array2.filter(({ pro_code }) => !pro_codes.has(pro_code));console.log(result);

沧海一幻觉

这是另一个优化的解决方案const arr1 = [{  des: "cont1",  note: "cont1",  pro_code: "XXY"}, {  des: "cont2",  note: "cont2",  pro_code: "NNB"}, {  des: "cont4",  note: "cont4",  pro_code: "QQA"}, {  des: "cont5",  note: "cont5",  pro_code: "GFD"}];const arr2 = [{  des: "cont1",  note: "cont1",  pro_code: "XXY"}, {  des: "cont2",  note: "cont2",  pro_code: "NNB"}, {  des: "cont3",  note: "cont3",  pro_code: "QAS"}];const results = arr2.filter(({ pro_code: id1 }) => !arr1.some(({ pro_code: id2 }) => id2 === id1));console.log(results);

波斯汪

简而言之,您的要求是过滤arr2并保留不在arr1.const arr3 = arr2.filter(function(arr2item) {  // only keep this item if it is not in arr1  return !arr1.some(function(arr1item) {    return arr1item.pro_code === arr2item.pro_code;  })});const arr1 = [{des: "cont1", note: "cont1", pro_code: "XXY"}, {des: "cont2", note: "cont2", pro_code: "NNB"}, {des: "cont4", note: "cont4", pro_code: "QQA"}, {des: "cont5", note: "cont5", pro_code: "GFD"}];const arr2 = [{des: "cont1", note: "cont1", pro_code: "XXY"}, {des: "cont2", note: "cont2", pro_code: "NNB"}, {des: "cont3", note: "cont3", pro_code: "QAS"}]const arr3 = arr2.filter(function(arr2item) {  return !arr1.some(function(arr1item) {    return arr1item.pro_code === arr2item.pro_code;  })});console.log(arr3);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript