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

Marco Pestrin
1 min readSep 29, 2022

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:

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:

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:

--

--