Home > Mobile >  JavaScript - Count the Objects in Array and Remove Duplicate Object
JavaScript - Count the Objects in Array and Remove Duplicate Object

Time:09-28

I have an array like this:

var objects = [{
    name: "brilliance_denali_(best)"
    shadowColor: "warmWhite"
    wattage: {upPrice: 10, value: '10W'}
},
{
    name: "brilliance_denali_(best)"
    shadowColor: "warmWhite"
    wattage: {upPrice: 10, value: '10W'}
},
{
    name: "brilliance_denali_(best)"
    shadowColor: "red"
    wattage: {upPrice: 12, value: '12W'}
},
{
    name: "bullet_lights"
    shadowColor: "blue"
    wattage: {upPrice: 28, value: '10W'}
}]

And I want to calculate the count based on name && shadowColor && wattage.value. Get the count and remove the duplicates with result array like:

var result = [{
    name: "brilliance_denali_(best)"
    shadowColor: "warmWhite"
    wattage: {upPrice: 10, value: '10W'},
    count: 2
},
{
    name: "brilliance_denali_(best)"
    shadowColor: "red"
    wattage: {upPrice: 12, value: '12W'},
    count: 1
},
{
    name: "bullet_lights"
    shadowColor: "blue"
    wattage: {upPrice: 28, value: '10W'},
    count: 1
}]

How can I achieve this result using array.reduce ?

CodePudding user response:

You use the classic indexOf trick.

const cleaned = yourlist.filter((entry, position) => {
  yourlist.findIndex(e => e.name === entry.name && ...) === position;
});

That is: remove any element that exists in the array, based on the findIndex function (which lets your find things based on a match function), but does NOT have the index of the element you're looking at right now.

CodePudding user response:

You can first do object count in array and then add that count to initial objects

var objects = [{
    name: "brilliance_denali_(best)",
    shadowColor: "warmWhite",
    wattage: {upPrice: 10, value: '10W'}
},
{
    name: "brilliance_denali_(best)",
    shadowColor: "warmWhite",
    wattage: {upPrice: 10, value: '10W'}
},
{
    name: "brilliance_denali_(best)",
    shadowColor: "red",
    wattage: {upPrice: 12, value: '12W'}
},
{
    name: "bullet_lights",
    shadowColor: "blue",
    wattage: {upPrice: 28, value: '10W'}
}]


const counter = objects.reduce((acc,curr)=>{
   const key = JSON.stringify(curr);
   acc[key] = (acc[key] || 0)   1;
   return acc;
}, {});

const result = [];

for (const key in counter){
  const finalObj = JSON.parse(key);
  finalObj.count = counter[key];
  result.push(finalObj);
}

console.log(result)

  • Related