I have an array that I need to find the highest value of so when I apply it to a Highchart I can color the background if it exceeds some dynamic number a user inputs.
My code looks like this:
<div id="highest"></div>
var array = {
data: [123, 234, 456, 789],
data: [321, 654, 987],
data: [963, 852, 741]
};
for (var i=0; i < array.data.length; i++){
var m = Math.max.apply(Math, array.data);
$('#highest').append('<div>'+m+'</div>');
}
all I get is the number
<div>963</div>
<div>963</div>
<div>963</div>
Your array variable isn't an array([]), it is an object({}). You have multiple items in the object with the key data, but only one value per key is allowed.
So you have essentially written this:
var array = {
data: [963, 852, 741]
};
Maybe you want something like this?
var array = [
{data: [123, 234, 456, 789]},
{data: [321, 654, 987]},
{data: [963, 852, 741]}
];
var values = [];
for (var i=1; i < array.length; i++) {
values.push.apply(values, array[i].data);
}
$('#highest').append('<div>' + Math.max.apply(Math, values) + '</div>');
or get rid of data entirely and just make it an array of arrays.
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