Cecilia Chan Cecilia Chan - 28 days ago 9
Javascript Question

find difference of daily comparison using javascript

[{date:'2017-8-1',count: 100},
{date:'2017-8-2',count: 200},
{date:'2017-8-3',count: 101},
{date:'2017-8-4',count: 123},
{date:'2017-8-5',count: 14},
{date:'2017-8-6',count: 12},
{date:'2017-8-7',count: 2},
{date:'2017-8-8',count: 3}] //today


I have 8 array item, I want to find the difference of each day. But I don't know how to calculate the difference of previous day. For example the difference between 2017-8-8 compare to 2017-8-7 is 1, how do I need to do the loop?

Answer Source

You can use forEach to calculate the difference between two adjacent count values in the array like this:

var data = [{date:'2017-8-1',count: 100},
{date:'2017-8-2',count: 200},
{date:'2017-8-3',count: 101},
{date:'2017-8-4',count: 123},
{date:'2017-8-5',count: 14},
{date:'2017-8-6',count: 12},
{date:'2017-8-7',count: 2},
{date:'2017-8-8',count: 3}];

var result = [];
data.forEach(function(obj, idx) {
  if(!idx) return;
  result.push(data[idx].count - data[idx-1].count);
});

console.log(result);