views:

36

answers:

2

Hi, I have some JSON which looks generally like this...

{"appJSON": [
{
"title":"Application Title",
"category":"Business", 
"industry":"Retail", 
"language":"English", 
"tags":[
        {"tags":"Sales"},{"tags":"Reporting"},{"tags":"Transportation"},{"tags":"Hospitality"}
       ], 
},
{
"title":"Airline Quality Assurance",
...
...
...]}

I'm looping through JSON to get an array of all of the unique Tags in the data.

My question is, now that I have an array of the different unique Tags in the JSON, how do I best determine the number of times each Tag occurs?

So basically I'm looking to generate a list of all of the tags found in the JSON (which I already have) with the number of times each one occurs (which I don't already have).

Thanks a lot in advance!

+2  A: 

I'm assuming when you find a new tag you check to see if you already have that tag somewhere. If you don't you add it to your list. Why not when you check do something like.

var nextTag=//get the next tag in the JSON list
var newTag=true;
for(var i=0;i<tags.length;i++){
  if(nextTag === tags[i]){
    tagCount[i]++;
    newTag=false;
    break;
  }
}
if(newTag){
  tags[tags.length]=nextTag;
  tagCount[tagCount.length]=1;
}

This uses two arrays where tagCount[i] is the number of times tag in tags[i] occurs. You could uses an object to do this or however you wanted to.

qw3n
+1  A: 

As an alternative, here's a function which will fill an associative array; the keys will be the tags and the values will be the number of occurrences of that tag.

var tagCounts = []; // Global variable here, but could be an object property or any array you like really

function countTags(tags, tagCounts)
{
    $.each(tags, function(i, item) {

        var tag = item.tags; // This would change depending on the format of your JSON

        if(tagCounts[tag] == undefined) // If there's not an index for this tag
            tagCounts[tag] = 0;

        tagCounts[tag]++;

    });
}

So you can call this function on any number of arrays of tags, passing in your tagCounts (totals) array, and it will aggregate the totals.

var tags1 = [{"tags":"Sales"},{"tags":"Reporting"},{"tags":"Transportation"},{"tags":"Hospitality"}];
var tags2 = [{"tags":"Reporting"},{"tags":"Transportation"}];
var tags3 = [{"tags":"Reporting"},{"tags":"Hospitality"}];

countTags(tags1, tagCounts);
countTags(tags2, tagCounts);
countTags(tags3, tagCounts);

Then you can read them out like so:

for(var t in tagCounts)
    // t will be the tag, tagCounts[t] will be the number of occurrences

Working example here: http://jsfiddle.net/UVUrJ/1/

qw3n's answer is actually a more efficient way of doing things, as you're only looping through all the tags once—but unless you have a really huge JSON source the difference isn't going to be noticeable.

Mark B