Home > Enterprise >  How to get the difference between latest and previous data in an array within one hour using javassc
How to get the difference between latest and previous data in an array within one hour using javassc

Time:12-08

I have this array of objects:

0: {time: '2021-12-02T23:53:54.062Z', value: 558316}
1: {time: '2021-12-03T00:53:53.959Z', value: 558452}
2: {time: '2021-12-03T01:53:53.934Z', value: 558588}
3: {time: '2021-12-05T23:53:48.617Z', value: 568039}
4: {time: '2021-12-06T00:53:48.609Z', value: 568174}
5: {time: '2021-12-06T01:53:48.545Z', value: 568309}
6: {time: '2021-12-06T02:53:48.480Z', value: 568444}
7: {time: '2021-12-06T03:53:48.393Z', value: 568579}

Question is how to get the difference of value per hour, for example value from 1: 558452 subtract to value from 0: 558316 equals 136. But do not subtract if current and previous value is not within one hour for example value from 3: 568039 subtract to value from 2: 558588, value from 3 is more than an hour from value from 2. So this two should not be subtracted, because it will get high value(9,451) in graph.

expected result:

{time: '2021-12-03T00:53:53.959Z', value: 136}
{time: '2021-12-03T01:53:53.934Z', value: 136}
{time: '2021-12-06T00:53:48.609Z', value: 135}
{time: '2021-12-06T01:53:48.545Z', value: 135}
{time: '2021-12-06T02:53:48.480Z', value: 135}
{time: '2021-12-06T03:53:48.393Z', value: 135}

CodePudding user response:

You could use map to calculate the difference, and then filter based on this..

eg.

var data = [
 {time: '2021-12-02T23:53:54.062Z', value: 558316},
 {time: '2021-12-03T00:53:53.959Z', value: 558452},
 {time: '2021-12-03T01:53:53.934Z', value: 558588},
 {time: '2021-12-05T23:53:48.617Z', value: 568039},
 {time: '2021-12-06T00:53:48.609Z', value: 568174},
 {time: '2021-12-06T01:53:48.545Z', value: 568309},
 {time: '2021-12-06T02:53:48.480Z', value: 568444},
 {time: '2021-12-06T03:53:48.393Z', value: 568579},
].map(d => (d.time = new Date(d.time), d));

const oneHour = 1000 * 60 * 60;

const temp = data.map((m, ix, a) => {
  if (ix > 0) {
    m.diff = a[ix].time - a[ix -1].time;
    m.value2 = a[ix].value - a[ix -1].value;
  } else {
    //make first one filter out as
    //there is no previous
    m.diff = oneHour   1;
  }
  return m;
})
.filter(m => m.diff < oneHour)
.map(m => ({
  time: m.time,
  value: m.value2
}));

console.log(temp);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related