Finding the difference between consecutive numbers in an array in javascript

I have the following array

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

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

B=diff(A) returns

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

I would like to know if there is any similar inline function in javascript?

+6
source share
3 answers

There is 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/

+2
source

If you prefer functional programming, here is 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 everything except the first element. map returns a new value for each of them, and the return value is the difference between the element and the corresponding element in (array un- slice d), therefore A[i] is the element before [i] in the slice.

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

+6
source
 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
source

Source: https://habr.com/ru/post/987753/


All Articles