21

I have the following array

A=[1,2,3,3,0] 

and if I want to calculate difference between consecutive numbers in an array. I could do it in Matlab with using built-in function (diff)

B=diff(A) returns

B = [1,1,0,-3]

I would like to know there is any similar built-in function in javascript?

0

4 Answers 4

26

If you prefer functional programming, here's a solution using map:

function diff(A) {
  return A.slice(1).map(function(n, i) { return n - A[i]; });
}

A little explanation: slice(1) gets all but the first element. map returns a new value for each of those, and the value returned is the difference between the element and the corresponding element in A, (the un-sliced array), so A[i] is the element before [i] in the slice.

Here is the jsfiddle : https://jsfiddle.net/ewbmrjyr/2/

Sign up to request clarification or add additional context in comments.

2 Comments

The code can be further simplified by using Arrow functions.
const diff = (A) => { return A.slice(1).map( (item,index) => { return item - A[index] } )}
13

There's no such built-in function, but writing one is simple:

function diff(ary) {
    var newA = [];
    for (var i = 1; i < ary.length; i++)  newA.push(ary[i] - ary[i - 1])
    return newA;
}
var A = [1, 2, 3, 3, 0];
console.log(diff(A)) // [1, 1, 0, -3]

here is the fiddle: https://jsfiddle.net/ewbmrjyr/1/

1 Comment

Thanks j08691, it works. I had thought that there might be a in-built method, then i should not reinvent the wheel.
3

The code can by simplified by using Array methods and Arrow functions:

var visitsArr = [38,29,18,29,28,18,24];

var diffs = visitsArr.slice(1).map((x,i)=> x-visitsArr[i]);

diffs.forEach((x,i) => console.log(
   `Visits from day ${i+1} to day ${i+2} increased by ${x}`
));

For more information, see

Comments

1
var a = [1,2,3,3,0] ;
function diff (arr){
    diffArr=[];
    for(var i=0; i<arr.length-1; i++){
        diffArr.push(arr[i+1]-arr[i]);

    }
    return diffArr;
}
alert(diff(a)); //[1,1,0,-3]

1 Comment

How is this fundamentally different from my answer? Seems like the same logic.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.