I have an array that may look like this...
var array = array(1,4,7,8,12,15);
The values in the array will always be integers, and always will go up, or could be the same as the previous, but at least won't become less.
Now i would like to loop through the array and find out which "step" has the biggest difference between it, so in my example that would be array keys 4&5 since from 8-12 == 4... but it might also happen that this would be multiple steps with the same values, let's say my array would be this..
var array = array(1,5,7,8,12,15);
then it would be 0&1 and 4&5....
I'm looking for a function that can return me this... oh and it has to be PureJs...
I hope someone can help me.
I'm not sure exactly what you want. But if you want the greatest jump:
var max=0;
for (i=1; i<array.length; i++)
max = Math.max(max,array[i]-array[i-1]);
If you want the first location at which this greatest jump occurs:
var max=0;
var firstLoc=0;
for (i=1; i<array.length; i++)
{
curJump = array[i]-array[i-1];
if (curJump > max)
{
firstLoc = i;
max = curJump;
}
}
If you want the last location at which this jump occurs:
var max=0;
var lastLoc=0;
for (i=1; i<array.length; i++)
{
curJump = array[i]-array[i-1];
if (curJump >= max)
{
lastLoc = i;
max = curJump;
}
}
If you want an array of all locations at which this max jump occurs:
var max=0;
var locs = [];
for (i=1; i<array.length; i++)
{
curJump = array[i]-array[i-1];
if (curJump == max)
{
locs.push(i);
} else if (curJump > max)
{
locs = [i];
max = curJump;
}
}
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