0

Pretty new to JS here and the array operations I'm used to in PHP obviously do not work in JS. I have an array of objects with a date (timestamp), a duration (number) and a mode (number):


  {
    "date": 111, //Not proper timestamp, just for the purpose of the question
    "duration": 1.8333333333333333,
    "mode": 2
  },
  {
    "date": 111,
    "duration": 3.4,
    "mode": 1
  },
  {
    "date": 111,
    "duration": 2.9833333333333334,
    "mode": 2
  },
  {
    "date": 222,
    "duration": 5.666666666666667,
    "mode": 1
  },
  {
    "date": 222,
    "duration": 8.266666666666667,
    "mode": 2
  },
  {
    "date": 222,
    "duration": 0.5666666666666667,
    "mode": 1
  },
  {
    "date": 333,
    "duration": 9.25,
    "mode": 2
  }
]

What I'm looking for is to sum the durations of objects that share the same date and mode. ex:

{
    "date": 111, //Not proper timestamp, just for the purpose of the question
    "duration": 3.4,
    "mode": 1
  },
  {
    "date": 111,
    "duration": 4.81,
    "mode": 2
  },
  {
    "date": 222,
    "duration": 6.2,
    "mode": 1
  },
  {
    "date": 222,
    "duration": 8.26,
    "mode": 2
  },
  {
    "date": 333,
    "duration": 9.25,
    "mode": 2
  }
]

I have tried creating and manipulating 2 dimensional arrays without success.

For instance looping on my initial data set and updating a result_array like so:

result_array[mode][date]+=duration;

Thx

PYG
  • 347
  • 1
  • 2
  • 8
  • 1
    Please share what you have already tried. – BenM Feb 19 '20 at 19:47
  • 2
    Use a Map to sum it up and then remap the map to your final list of objects. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map – Joel Harkes Feb 19 '20 at 19:51
  • 1
    `Object.values(durations.reduce((obj, dur) => { const key = \`${dur.date}-${dur.mode}\`; if (obj[key]) { obj[key].duration += dur.duration; } else { obj[key] = { ...dur }; } return obj; }, {}))` – epascarello Feb 19 '20 at 20:04
  • @epascarello that works perfectly! Thx! – PYG Feb 19 '20 at 22:23
  • @epascarello I'm analyzing your answer to understand the technique. Could you explain to me the difference between obj[key] and obj in your answer? Thx. – PYG Feb 20 '20 at 06:33
  • not sure what you mean the difference.... Basic of reduce, you have an object, you set a property in the object, you return the object, – epascarello Feb 20 '20 at 14:17
  • I read the docs today. Well made and comprehensive, I got my explanation. – PYG Feb 20 '20 at 21:09

0 Answers0