简体   繁体   English

我想根据它们的 id 对两个数组的对象进行联合

[英]I want to take union on objects of two array based on their id

Let suppose I have two array假设我有两个数组

let array1 = [{id: 1,name: "a"},{id: 2,name: "b"}]
let array2 = [{id: 1,name: 'c'},{id: 3,name: 'd'}]

and I want the resulting array to be like so我希望结果数组像这样

let result = [{id: 1,name: 'c'},{id: 2,name: 'b'},{id: 3,name: 'd'}]

So if the second array has an object and the first array also has an object with the same id then replace the first object with the second array object.因此,如果第二个数组有一个对象,而第一个数组也有一个具有相同 id 的对象,则将第一个对象替换为第二个数组对象。 Currently, I have try below code but it checks for each value to match and I want to match on id based only目前,我尝试了下面的代码,但它检查每个值是否匹配,我只想根据 id 进行匹配

const uniqueArray = this.servicesdata.filter((item, index) => {
        const _item = JSON.stringify(item);
        return (
          index ===
          this.servicesdata.findIndex(obj => {
            return JSON.stringify(obj) === _item;
          })
        );
      });
      console.log(uniqueArray);

Here's a O(NlogN) approach.这是一个O(NlogN)方法。

let array1 = [{id: 1,name: "a"},{id: 2,name: "b"}] // Let's say its size is N1
let array2 = [{id: 1,name: 'c'},{id: 3,name: 'd'}] // Let's say its size is N2
let duplicate  = new Set() // A set to check for duplicate elements
let result = array2
array2.forEach((item)=>{ // O(N2logN2)
    duplicate.add(item.id);
})
array1.forEach((item)=>{ // O(N1logN2)
    // If `duplicate` does NOT have `item.id`, that means it's unique in array1, so add it to result
    // Otherwise, skip it because for duplicates, we want value from array2
    if(!duplicate.has(item.id))
        result.push(item);
})
// Overall complexity of approach - O(N2logN2) + O(N1logN2) ==> O(NlogN)
console.log(result);

Output:输出:

[ { id: 1, name: 'c' },
  { id: 3, name: 'd' },
  { id: 2, name: 'b' } ]

With lodash you can use unionBy :使用 lodash 你可以使用unionBy

 let array1 = [{id: 1,name: "a"},{id: 2,name: "b"}] let array2 = [{id: 1,name: 'c'},{id: 3,name: 'd'}] console.log(_.unionBy(array2, array1, 'id'))
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM