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.
- Let's start with the
prev
variable holding the first value of the array. - We need to store the contents of the final array
fin
somewhere. - Now let's have an incremental loop starting from the second index to the end.
- Find the difference and push into the final array
fin
. - 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()
.