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?
Given an unsorted array of numbers, write a function that returns true if the array consists of consecutive numbers. Examples: a) If the array is {5, 2, 3, 1, 4}, then the function should return true because the array has consecutive numbers from 1 to 5.
If we denote the 1st number as n, then the consecutive numbers in the series will be n, n+1, n+2, n+3, n+4, and so on. For any two consecutive odd numbers, the difference is 2. For example, 3 and 5 are two consecutive odd numbers, their difference = 5 - 3 = 2.
diff() is a numpy array function that finds the difference numbers in an array. The np. diff() function can be applied to a single array and multiple arrays. If a single array is passed then the difference is found by res[i] = arr[i+1] – arr[i].
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-slice
d array), so A[i]
is the element before [i]
in the slice.
Here is the jsfiddle : https://jsfiddle.net/ewbmrjyr/2/
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With