Shayne Shayne - 2 months ago 7
Javascript Question

Javascript counting number of times an element is repeated

I have the following code snippet in my JavaScript patch in quartz composer and need to loop in through the entire structure to find how many of each element there are and output an array of each element total. I am able to loop through the StructureIn to compare it to Title 0 and create and array with title 0 as the key and the number of repeats as the value. What I need to do is figure out how to loop through all the Title elements (there are 49 of em) to produce the desired array. Any assistance would be greatly appreciated.

var result = new Object();
var MySTR = new Object();

result.structureOut = new Object();
k = 1;

for(i = 0; i < structureIn[1].length; i++) {
if(structureIn[1][i][1] == Title[0])
MySTR[Title[0]] = k++;
}

result.structureOut = MySTR;
return result;

Answer

It seems like you want to do something like this:

var result = new Object();
var MySTR= new Object(); 

result.structureOut = new Object();
for(j = 0; j <49; j++)
{
   MySTR[Title[j]] = 0;
}

for(i = 0; i <structureIn[1].length; i++)
{
    for(j = 0; j <49; j++)
    {
       if(structureIn[1][i][1] == Title[j])
       MySTR[Title[j]]++;
    }
}

result.structureOut=MySTR;
return result;

You basically loop through all items in the structure and compare them to all items in Title. The first loop initializes the results to 0, so you don't have to keep track of the k variable you had anymore.

Comments