美文网首页
JS取出两个数组的不同或相同元素

JS取出两个数组的不同或相同元素

作者: 墨芊baby | 来源:发表于2019-03-26 18:16 被阅读0次

取出两个数组中code不等于name的那一项,并以一个新数组的形式展示

data(){
arr1: [
      {name: 'wxl1'},
      {name: 'wxl2'},
      {name: 'wxl3'},
      {name: 'wxl4'},
],
arr2: [
     {code: 'wxl1'},
     {code: 'wxl2'},
     {code: 'wxl3'},
]
let obj = {} //临时对象
let arrResult = []
this.arr2.forEach(function(item,index){
  obj[item.code] = true //将数组arr2中的元素值作为obj 中的键,值为true;
})
console.log(obj) //{wxl1: true, wxl2: true, wxl3: true}
this.arr1.forEach(function(item,index){
  if(!obj[item.name]){  //找不同  相同去掉取反即可
    arrResult.push(item.name) //通过此对象key的布尔值来作判断,没有则显示underfind取反为true
  }
})
console.log(arrResult)
结果:
['wxl4'];

相关文章

网友评论

      本文标题:JS取出两个数组的不同或相同元素

      本文链接:https://www.haomeiwen.com/subject/sbunvqtx.html