Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to Remove Duplicate Value From Array of object And Update Object Property Using JavaScript

I try many ways to solve this. I can remove duplicate values. but the problem is updating total_product value. How can I do this? Give me some hints.

This is my Main Array :

 const colors = [
    { "name": "Black", "total_product": 1 },
    { "name": "Black", "total_product": 1 },
    { "name": "White", "total_product": 1 },
    { "name": "White", "total_product": 1 },
    { "name": "White", "total_product": 1 },
    { "name": "White", "total_product": 1 },    
]

I Want Like This :

 const colors = [
    { "name": "Black", "total_product": 2 },
    { "name": "White", "total_product": 4 }         
]

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

It’s a good case for reduce which "boils down" an array to an accumulator value. Here, reduce (doc) can be used to create objects that count occurrences of each name…

const colors = [
    { "name": "Black", "total_product": 1 },
    { "name": "Black", "total_product": 1 },
    { "name": "White", "total_product": 1 },
    { "name": "White", "total_product": 1 },
    { "name": "White", "total_product": 1 },
    { "name": "White", "total_product": 1 } 
];

const counts = colors.reduce((acc, obj) => {
  if (!acc[obj.name]) acc[obj.name] = { name: obj.name, total_product: 0 };
  acc[obj.name].total_product++;
  return acc;
}, {});
const result = Object.values(counts);
console.log(result);

The intermediate value counts produced by reduce looks like this…

{
  "Black": {
    "name": "Black",
    "total_product": 2 // <- incremented each time we found a "Black"
  },
  "White": {
    "name": "White",
    "total_product": 4 // <- incremented each time we found a "White"
  }
}

Object.values(), like the name implies, makes an array of the values.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading