Matt Andrews - 1 year ago 62
Javascript Question

# How can I compute the difference between array values, then average them?

I'm trying to do this in a functional way so although there are some methods I can already think of, I suspect there's a more elegant map/reduce-style technique.

Given an array like this:

[0, 47.22, 72.65, 126.93, 155.02, 307.46, 410.02, 417.21,
507.86, 510.466, 580.88, 661.29, 685.14, 695.86, 780.94,
913.2, 1352.33, 1382.99, 1435.73, 1462.03, 1495.38, 1518.03,
1523.58, 1544.3, 1591.21, 1612.03, 1665.99, 1672.62, 11.02, 22.791]

I want to compute the difference between each item and its following value, eg:

[47.22, 25.43, 54.28] // etc

(these values are timestamps for chat messages – I want to effectively see how long gaps were between messages, and then calculate the average for this user).

I was looking at
reduce()
but struggling to see how to make it do what I need. Is there an elegant way to do this or is my best bet a
for
loop which looks ahead to the next array item and does the calculation there?

Using a forEach loop to add the difference between adjacent elements into a new array:

var arr = [0, 47.22, 72.65, 126.93, 155.02, 307.46, 410.02, 417.21,
507.86, 510.466, 580.88, 661.29, 685.14, 695.86, 780.94,
913.2, 1352.33, 1382.99, 1435.73, 1462.03, 1495.38, 1518.03,
1523.58, 1544.3, 1591.21, 1612.03, 1665.99, 1672.62, 11.02, 22.791];

var result = [];

arr.forEach(function(element, index, array) {
this.push(((array[index + 1] || 0) - element).toFixed(3));
}, result);

console.log(result);
.as-console-wrapper{top:0;max-height:100%!important;}

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download