This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by Marco Pestrin
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);
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 },
}
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]);
This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by Marco Pestrin
Marco Pestrin | Sciencx (2022-09-29T18:19:47+00:00) How to subtract objects from an array of objects by id in Javascript. Retrieved from https://www.scien.cx/2022/09/29/how-to-subtract-objects-from-an-array-of-objects-by-id-in-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.