-1

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. Currently, I have try below code but it checks for each value to match and I want to match on id based only

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);
Musawer Shah
  • 314
  • 1
  • 9
  • 1) Please show us what have you tried so far to achieve this. 2) Why there is no object with `name: a` in the `result` – Maheer Ali Dec 31 '19 at 06:09
  • because the object with name: a and object with name: c have same id that's why it will be replaced by object from array 2 – Musawer Shah Dec 31 '19 at 06:10

2 Answers2

0

Here's a O(NlogN) approach.

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' } ]
Ajay Dabas
  • 1,404
  • 1
  • 5
  • 15
0

With lodash you can use 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>
Mervyn
  • 543
  • 4
  • 15