Reputation: 35
I have a series of values plotted on a Line Chart. These values are inputs, from a user, via a HTML form.
Example 1 values : 130, 136, 142, 148, 149, 159.
Example 2 values : 130, 140, 150, 175, 180, 200.
Is it possible to have a script that can select the value that precedes the biggest increase?
So for example 1 - the value of interest would be 149 - because 149 to 159 is the biggest increase, value to value.
And for example 2 - the value of interest would be 150 - for the same reason.
Please advise.
Here is my code with your help so far :
$(document).ready(function() {
$.ajax({
url : "includes/dataFile.php",
dataType : "JSON",
success: function(data) {
google.charts.load('current', {'packages' : ['corechart', 'line']});
google.charts.setOnLoadCallback(function() { drawChart(data); });
}
});
function drawChart(caldata) {
var data = new google.visualization.DataTable(caldata);
data.addColumn('number', '');
data.addColumn('number', '');
data.addColumn('number', '');
var dataArray = [];
$.each(caldata, function(i, obj) {
dataArray.push([parseFloat(obj.stage1_rate), parseInt(obj.stage1), parseInt(obj.stage1_duration)]);
dataArray.push([parseFloat(obj.stage2_rate), parseInt(obj.stage2), parseInt(obj.stage2_duration)]);
dataArray.push([parseFloat(obj.stage3_rate), parseInt(obj.stage3), parseInt(obj.stage3_duration)]);
dataArray.push([parseFloat(obj.stage4_rate), parseInt(obj.stage4), parseInt(obj.stage4_duration)]);
dataArray.push([parseFloat(obj.stage5_rate), parseInt(obj.stage5), parseInt(obj.stage5_duration)]);
dataArray.push([parseFloat(obj.stage6_rate), parseInt(obj.stage6), parseInt(obj.stage6_duration)]);
});
data.addRows(dataArray);
var linechart_options = {
.....
};
var linechart = new google.visualization.LineChart(document.getElementById('linechart_div'));
linechart.draw(data, linechart_options);
function getMaxDelta(array) {
return array[array.reduce(function (r, a, i, aa) {
return aa[r + 1] - aa[r] < aa[i + 1] - a ? i : r;
}, 0)];
}
console.log(getMaxDelta([130, 136, 142, 148, 149, 159]));
}
});
Upvotes: 1
Views: 138
Reputation: 386600
You could save the index with the greatest delta with Array#reduce
and check if the actual value and the following item is greater than the saved pair.
function getMaxDelta(array) {
return array[array.reduce(function (r, a, i, aa) {
return aa[r + 1] - aa[r] < aa[i + 1] - a ? i : r;
}, 0)];
}
var array1 = [130, 136, 142, 148, 149, 159],
array2 = [130, 140, 150, 175, 180, 200];
console.log([array1, array2].map(getMaxDelta));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 1