merge two object arrays with only unique entries in typescript

To merge two arrays of objects with unique entries, we can use the concat method to combine the two arrays into a new array, followed by the reduce method to filter out any duplicates based on a property of the objects.

Assuming the two arrays have the same object structure, we can use the following code:

index.ts
interface MyObject {
  id: number;
  name: string;
  // other properties...
}

const array1: MyObject[] = [/* ... */];
const array2: MyObject[] = [/* ... */];

const mergedArray = array1.concat(array2).reduce((acc: MyObject[], obj: MyObject) => {
  if (!acc.some(item => item.id === obj.id)) {
    acc.push(obj);
  }
  return acc;
}, []);
339 chars
16 lines

In this code, we first use the concat method to merge the two arrays into a new array mergedArray. Then we use the reduce method to iterate through each object in the array and check if it already exists in the accumulator (acc) array, which starts as an empty array []. We use the some method to check if any object in acc has the same ID as the current obj. If not, we add the obj to the accumulator and return it. If there is a match, we simply return acc without adding the obj.

gistlibby LogSnag