Reputation: 2315
I'm trying to find the fastest way to calculate the difference with previous value in an array with javascript.
var arr = [10,20,30,40,50];
I want to obtain the following result (10-20,20-30,30-40,40-50)
Upvotes: 1
Views: 393
Reputation: 318302
var result = arr.map(function(x,i) {
return x - arr[i+1]
}).filter(Number);
// result - [-10, -10, -10, -10]
var arr = [10,20,30,40,50];
var result = arr.map(function(x,i) {
return x - arr[i+1]
}).filter(Number);
document.body.innerHTML = '<pre>' + JSON.stringify(result, null, 4) + '</pre>';
Upvotes: 5