Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
September 29, 2022 06:19 pm GMT

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);

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]);

Original Link: https://dev.to/pestrinmarco/how-to-subtract-objects-from-an-array-of-objects-by-id-in-javascript-6e9

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To