I have an array of objects like this:
var chartData = [{count: 0, idTag: "24"}
{count: 0, idTag: "25"}
{count: 0, idTag: "26"}]
My code does some work and generates a number (totalValue
). If totalValue
matches the idTag
, its count
gets increased by one:
for (i=0; i<timesFlipped; i++) {
totalValue = runTrial();
for (j=0; j<chartData.length; j++) {
if (chartData[j].idTag === totalValue) {
chartData[j].count += 1;
break;
}
}
}
This is a simple example, but chartData
could hold a few dozen objects, and timesFlipped
can be hundreds of thousands of iterations.
Is this the best way to change the count
value based on matching the idTag
value? Is there a way to just find the index of the array with the correct idTag
value without iterating over the whole array of objects?
Here's the page I'm working on if you want more context: http://blue.butler.edu/~aazman/coupling/
Update:
Thanks for all the suggestions. I kinda formed my own solution based on what I saw. A bit more background about the project which led me to my solution:
- The length of
chartData
and the min idTag value are calculated based on user inputs when they click submit - Once
min
andlength
are calculated (thus the max idTag is known),chartData
is iteratively initialized:
var min = 23-5*numNickel-numPenny; //numNickel & numPenny are the user inputs
var length = 5*(2*numNickel+1)+2*numPenny;
var tempTag = min;
for (j=0;j<length;j++) {
chartData[j] = {count: 0, idTag = tempTag};
tempTag++;
}
- For reasons particular to the rules of the game, the idTag values (however many there are) are symmetrically centered around
idTag:25
(e.g. idTags = {24, 25, 26} or idTags = {20,21,22,23,24,25,26,27,28,29,30}. No matter the length ofchartData
, the length will always be odd andidTag:25
will always be the[(chartData.length-1)/2]
'th index.
Thus, if the idTags for chartData
are {20,21,22,23,24,25,26,27,28,29,30}
and if runTrial()
gives totalValue = 22
, then idTag:22
will always be at index (totalValue - min)
.
So I changed the initialization of chartData and the way the count gets increased to:
for (j=0; j<length; j++) {
chartData[j] = {count: 0}; //based on what I'm doing with chartData next, I need each index to still be an object
}
for (i=0; i<timesFlipped; i++) {
totalValue = runTrial();
var index = totalValue - min;
chartData[index].count++;
}
So thanks all for your help :)