Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

如何优雅的取两个数组对象相同下标的不同值?

假设两个数组对象为

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)
          }
        }

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
const result = arr2.filter(item => arr1.some(r => r.id==item.id&&r.name!=item.name))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...