I’ve looked around and have not found any answers for this. The problem seems pretty simple at first.
Lets say we have an array like this. We can assume that the array will ALWAYS have some equal thing it counts up by.
[1.0,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2.0]
The answer to above would 1.1
Another example might be an array like this.
[0.2,0.4,0.6,0.8,1.0,1.2,1.4]
This answer would 0.2
One possible solution is I could read the first and second parameters of the array and capture the difference and that will be my ‘step’. Is this the best way to go about doing this? Is there any downsides to this approach?
if the array was counting downward like this
[0.8,0.6,0.4,0.2], then what?
In this case I need the answer -0.2, my answer would not work, and taking the absolute value would give me 2 not -2.
>Solution :
This is the same as taking the common difference of an arithmetic progression in mathematics. You can just subtract a term from the previous term, and you’ll get the difference. Here is how the array would look in general terms:
[a, a + d, a + 2d, a + 3d, ...]
So from this you can easily see that if you perform (a + d) - (a), you’ll get d. Subtracting any element from the previous element will yield the same result. So the simplest way to do this would be:
const getStep = array => (array[1] - array[0]);
Demonstration using your three provided arrays:
const getStep = array => (array[1] - array[0]);
console.log(getStep([1.0,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2.0]));
console.log(getStep([0.2,0.4,0.6,0.8,1.0,1.2,1.4]));
console.log(getStep([0.8,0.6,0.4,0.2]));
Note that the above values may be inaccurate as they’re floating point numbers (Floating point math is broken) but you can just round it to the nearest x-th decimal place (here’s a solution with a 1/10th rounding, for instance):
const getStep = array => Math.round((array[1] - array[0]) * 10) / 10;
console.log(getStep([1.0,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2.0]));
console.log(getStep([0.2,0.4,0.6,0.8,1.0,1.2,1.4]));
console.log(getStep([0.8,0.6,0.4,0.2]));