I have an array of objects like this:
var chartData = [{count: 0, idTag: \"24\"}
{count: 0, idTag: \"25\"}
{count: 0, idTag: \"
I would suggest using client side database storage mechanisms, and let the queries do the counting for you.
This makes it more overseeable and reduces menory warnings from various virusscanners, plus you dont need to refetch data everytime.
Another approach would be to use a server side database and retrieve the values you want via json.
another aproach toprevent browser freeze is to let your loop run in a webworker so its a thread and doesnt lock the browser.
If you're free to change the structure of chartData, why not just make it a hash instead of an array?
var chartData = {24: 0,
25: 0,
26: 0};
And then the loop becomes
for (i=0; i<timesFlipped; i++) {
chartData[runTrial()]++;
}
You could create another object which points to the objects in the chartData array, like so:
var idToChart = {};
for (var i = 0; i < chartData.length; i++) {
var currChart = chartData[i];
idToChart[currChart.idTag] = currChart;
}
and then use
var chart = idToChart[totalValue];
chart.count++;
Accessing the object's property should be faster than looping through the array each time.
If, as @zerkms pointed out, your array is sorted by idtag
, you wouldn't even need to create another object and could access the array directly. Ideally, chartData
would start in the idToChart
or sorted array format.
I would rather maintain a intermediate hash with a "idTag" value as a key and its count as value, perform the operation with for loop, then generate charData from the intermediate hash once the for loop completes.