Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

假设两个数组对象为

arr1: [{id: 1, name: 'a'}, {id: 2, name: 'b'}, {id: 3, name:'c'}],
arr2: [{id: 1, name: 'a'}, {id: 2, name: 'c'}, {id: 3,name: 'b'}],

我目前的方法是

let arr3 = []
        for (let i in this.arr2) {
          let obj2 = this.arr2[i]
          let name2 = obj2.name
          let flag = false
          for (let k in this.arr1) {
            k = parseInt(k) + parseInt(i)
            if (k <= this.arr2.length - 1) {
              let obj1 = this.arr1[k]
              let name1 = obj1.name
              if (name2 == name1) {
                flag = true
                break
              }
              if (flag == false) {
                arr3.push(obj2)
                break
              }
            }
          }
        }

得出arr3 = [{id:2,name:'c'},{id:3,name:'b'}]
但是感觉代码不好看,试了一下some的用法

for (let i in this.arr2) {
          const item = this.arr2[i].name
          if (!this.arr1.some(e => e.name == item)) {
            arr3.push(item)
          }
        }

得到的为空数组,也没有报错,不知道是什么原因,想请问各位有更简洁的方法吗?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.9k views
Welcome To Ask or Share your Answers For Others

1 Answer

const result = arr2.filter(item => arr1.some(r => r.id==item.id&&r.name!=item.name))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...