0

I have a function which will produce array value from currentTime of timer by clicking button. In this case this is the result:

var data_catch = ["0", "24.871604", "27.1788", "29.69", "29.100", "30.570661"];

And then I need to get duration between array value with rules "the next value will reduce by previous value" which leads me to use this way:

var data_duration = [];
for (var i = 1; i < data_catch.length; i++) {
    data_duration.push(data_catch[i]-data_catch[i-1]);
}
console.log(data_duration);

The value of data_duration should never be minus, because the timer always going ahead and the currentTime always have bigger value than previous currentTime. But in this case the result of data_duration is :

data_duration = [
  24.871604, 
  2.3071959999999976, 
  2.5112000000000023, 
  -0.5899999999999999, 
  1.4706609999999998
];

The result have one minus value because of this reduction 29.100 - 29.69 Why this is happen and how to fix this? Please help me..

fandiahm
  • 113
  • 2
  • 7

1 Answers1

2

You can use Math.abs to get the absolute value.Also mathematically 29.69 is greater than 29.100

var data_catch = ["0", "24.871604", "27.1788", "29.69", "29.100", "30.570661"];
var data_duration = [];
for (var i = 1; i < data_catch.length; i++) {
  data_duration.push(Math.abs(data_catch[i] - data_catch[i - 1]));
}

console.log(data_duration);
brk
  • 48,835
  • 10
  • 56
  • 78
  • This is solved my problem. I don't know about this Math.abs() I will keep learning. Thank you very much... – fandiahm Jul 16 '17 at 14:04
  • this is not a good solution, you need to set the correct value to the data_catch when user click the button. – Atmahadli Jul 16 '17 at 14:19
  • @Atmahadli the objective of the solution is to demonstrate the usage of `Math.abs()`. The problem does not describe any `button`. I am sorry if i have missed any requirement – brk Jul 16 '17 at 14:21
  • sometimes some people didn't know the exact problem and ask wrong question. as i understand the problem here is why the data_catch array is decreased from 29.69 to 29.100?(note that it is from the user click from time to time) by using abs the result is abs(29.100-29.69)=0.59; I think the correct data is 29.069 so the correct result should be 29.100-29.069=0.031; – Atmahadli Jul 16 '17 at 14:36