JosepB
JosepB

Reputation: 2315

Fastest way to calculate the the difference from previous value in an array

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

Answers (2)

adeneo
adeneo

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

AmmarCSE
AmmarCSE

Reputation: 30587

var results = [];
var arr = [10,20,30,40,50]; 

for(var i = 0; i < arr.length - 1; i++){
results.push(arr[i] - arr[i+1]);
}

See it in action

Upvotes: 2

Related Questions