abarc
abarc

Reputation: 119

Remove duplicates in a JavaScript object array and sum the entries

I have an object with two properties: x and y, of types String and number respectively.

The corresponding (x,y) values are used to plot a time series using Plotly in an Express.js application, with x taking the format 2013-10-04T22:23.

Now say I have an object with duplicate x values, and I need to remove the duplicates, leaving only one entry for that x value and sum up the corresponding y values, again leaving only one corresponding y value.

For example:

var data = [
               {
                   x: ["2013-10-04 22:22", "2013-10-04 22:22", "2013-10-04 22:22", 
                       "2013-12-12 15:15"],
                   y: [1, 1, 1, 6]
               }
           ];

I want to sum up the y values for the 2013-10-04 22:22 x values, leaving only one x value y value pair like so:

data = [
           {
               x: ["2013-10-04 22:22", 
                   "2013-12-12 15:15"],
               y: [3, 6]
           }
       ];

How would one do this?

Upvotes: 0

Views: 337

Answers (1)

soltex
soltex

Reputation: 3551

You can create a function that receives an object and manipulate the object the way you want:

const obj = {
  x: ["2013-10-04 22:22", "2013-10-04 22:22", "2013-10-04 22:22", "2013-12-12 15:15"],
  y: [1, 1, 1, 6]
}

function removeObjDuplicates ({ x, y }) {

  const occurrences = {};

  for (let i = 0; i < x.length; i++) {
      occurrences[x[i]] = (occurrences[x[i]] || 0) + y[i];
  }

  return {
    x:  Object.keys(occurrences),
    y:  Object.values(occurrences),
  }
}

removeObjDuplicates(obj) will return:

{
   x: ["2013-10-04 22:22", "2013-12-12 15:15"],
   y: [3, 6]
}

Upvotes: 2

Related Questions