Calculation of Range between Array Elements

Recently I saw a question in Stack Overflow, where it asks how to calculate the count between each array element using JavaScript. Well, this is my take on it.

var myArray = [2, 3, 6, 11];  

Giving the above array as input will have a desired output of:

[1, 3, 5]

The reason would be as follows:

02    03    06    11         Input:  Original Array  
   01    03    05            Output: Difference between elements.

So I wrote a quickie, this way. Use a counter and previous flag.

  1. Let's start with the prev variable holding the first value of the array.
  2. We need to store the contents of the final array fin somewhere.
  3. Now let's have an incremental loop starting from the second index to the end.
  4. Find the difference and push into the final array fin.
  5. Update the prev value to represent the current value.

We can do it this way:

var a = [2, 3, 6, 11];  
var prev = a[0];  
var fin = [];  
for (var i = 1; i < a.length; i++) {  
  fin.push(a[i] - prev);
  prev = a[i];
}
console.log(fin);  

The above will output the desired output of [1, 3, 5]. But I found out that there's more elegant approach for this using the new syntax and new array function Array.prototype.reduce().



comments powered by Disqus