Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding difference between consecutive numbers in an array in javascript

Tags:

javascript

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?

like image 906
mystackoverflow Avatar asked May 22 '15 14:05

mystackoverflow


People also ask

How do you compare consecutive elements in an array?

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.

How do you find the difference of consecutive numbers?

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.

How do you find the difference between numbers in an array?

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].


2 Answers

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/

like image 105
Roy J Avatar answered Oct 25 '22 14:10

Roy J


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/

like image 22
j08691 Avatar answered Oct 25 '22 16:10

j08691