DEV Community

Marco Pestrin
Marco Pestrin

Posted on

3

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay