Home > Mobile >  Typescript/Javascript Count duplicate values based on 2 parameters
Typescript/Javascript Count duplicate values based on 2 parameters

Time:10-14

I am having a hard time manipulating my data to be useful in a bar chart.

This is the data is ended up with after mapping it with only the properties i need:

const data = [
    {
        date: "2021-10-10",
        serialNumber: "4A6211B92417A7DB"
    },
    {
        date: "2021-10-11",
        serialNumber: "5B6211B92417A7DB"
    },
    {
        date: "2021-10-12",
        serialNumber: "5B6211B92417A7DB"
    },
    {
        date: "2021-10-12",
        serialNumber: "4A6211B92417A7DB"
    },
    {
        date: "2021-10-12",
        serialNumber: "4A6211B92417A7DB"
    },
    {
        date: "2021-10-12",
        serialNumber: "4A6211B92417A7DB"
    }
];

What i want to have is the following: a count of the duplicates based on the date per serialNumber. It would look like this:

const solution = [
    {
        serialNumber: "4A6211B92417A7DB",
        count: 3,
        date: "2021-10-12",
    },
    {
        serialNumber: "5B6211B92417A7DB",
        count: 1,
        date: "2021-10-12",
    },
    {
        serialNumber: "5B6211B92417A7DB",
        count: 1,
        date: "2021-10-11",
    },
    {
        serialNumber: "5B6211B92417A7DB",
        count: 1,
        date: "2021-10-10",
    },
]

What i came up with was the following:

array.forEach(function(obj: any) {
       const key = JSON.stringify(obj.serialNumber)
       counts[key] = (counts[key] || 0)   1
    });

but then it only count them based on 1 parameter and i also need the count per date aswel. How do you do this?

CodePudding user response:

You can use a 'group-by' with a composite key formed of the date and serial number. Here using a for..of loop to accumulate into an object, creating the composite key using a template literal and then assigning the Object.values() as the result.

const data = [{ date: '2021-10-10', serialNumber: '4A6211B92417A7DB', }, { date: '2021-10-11', serialNumber: '5B6211B92417A7DB', }, { date: '2021-10-12', serialNumber: '5B6211B92417A7DB', }, { date: '2021-10-12', serialNumber: '4A6211B92417A7DB', }, { date: '2021-10-12', serialNumber: '4A6211B92417A7DB', }, { date: '2021-10-12', serialNumber: '4A6211B92417A7DB', },];

const counts = {};
for (const datum of data) {
  const k = `${datum.date}_${datum.serialNumber}`;
  // using OR short circuit
  (counts[k] || (counts[k] = { ...datum, count: 0 })).count  = 1;
  
  // alternativley with logical nullish assignment if available
  //(counts[k] ??= { ...datum, count: 0 }).count  = 1;
}

const result = Object.values(counts);

console.log(result);

  • Related