DEV Community

Marco Pestrin
Marco Pestrin

Posted on

How to subtract objects from an array of objects by id in Javascript

Considering the case of wanting to add data to the database but without having duplicates.

Therefore we have two objects: one with my data in the database and the second with the data to add.

Respectively in the example called: records and mainArr.

As the title says, in this case we have to subtract the elements of the first (records) from the second (mainArr) array by id.

There are many algorithms that can be adopted, below is an example:

const records = [
  {
    id: 1,
    name: "example1"
  },
  {
    id: 2,
    name: "example2"
  },
  {
    id: 3,
    name: "example3"
  },
  {
    id: 4,
    name: "example4"
  },
];

const mainArr = [
  {
    id: 3,
    name: "example3"
  },
  {
    id: 4,
    name: "example4"
  },
  {
    id: 5,
    name: "example5"
  },
  {
    id: 6,
    name: "example6"
  },
];

const recordsById = records.reduce((ac, record) => {
  if (record.id) {
    return {
      ...ac,
      [record.id]: record
    }
  }
  return ac
}, {});

const objClean = mainArr.filter((item) => {
  const isDuplicated = recordsById[item.id];
  return !isDuplicated;
});

console.log(objClean);
Enter fullscreen mode Exit fullscreen mode

We use reduce to conveniently obtain an array of objects with the identifier as key and the object itself as value.

We will then have a result similar to:

 recordsById: {
    1: { name: "example1", id: 1 },
    2: { name: "example2", id: 2 },
    3: { name: "example3", id: 3 },
    4: { name: "example4", id: 4 },
  }
Enter fullscreen mode Exit fullscreen mode

Then through the filter method we can check if an element of my second array (mainArr) contains an element of the created mapping.

We will output my clean object (objClean).

Below is a more compact version of the same logic:

const recordsById = records.reduce((ac, record) => {
  return record.id ? { ...ac, [record.id]: record } : ac;
}, {});

const objClean = mainArr.filter(item => !recordsById[item.id]);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)