0

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?

1 Answer 1

2

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]
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this is what I was looking for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.