skip to Main Content

I have some data that looks like this:

{
  "data": [
    {
       "tags": [
           "design",
           "development",
           "code",
           "foo",
           "bar"
        ],
        "views": [
           "81"
        ]
        ...
    },
    {
       "tags": [
           "design",
           "foo",
           "photoshop",
           "alice",
           "bob"
         ],
        "views": [
           "28"
         ]
     ...
    }

What I’m hoping to do is loop through each data item, count up the tags, and then display how many times each one occurs. I don’t want to go query each tag manually, though.

So ideally, I’d like it to display like this:

foo: 2
design: 2
alice: 1 

and so on. Eventually, I’m hoping to incorporate it into a chart using Highcharts, Amcharts, or something similar?

The closest I’ve managed is this, taken from another solution on this site (and this doesn’t create a full display, but I was first trying to get to grips with counting the values themselves, in any way possible):

$.getJSON('myarray.json', function(data) {

var occurrences = 0;
for (var i = 0; i < data.data.length; i++) {
  if (data.data[i].tags == "foo") {
    occurrences++;
  }
}

console.log(occurrences);

});

But this output is incorrect. Any help at all would be appreciated. Once again, I would like to look through the tags for each dataset, and output a count for how many times each one occurs (ideally ranked in descending order).

5

Answers


  1. if (data.data[i].tags.indexOf("foo") != -1)
    
    Login or Signup to reply.
  2. You correctly loop through each item, but you forget that “tags” in each item is a list of items as well.

    $.getJSON('myarray.json', function(data) {
    
      var tagcount = {};
      for (var i = 0; i < data.data.length; i++) {
        var item = data.data[i];
        if( item.tags != undefined ) {
          for (var j = 0; j < item.tags.length; j++) {
            var tag = item.tags[j];
            if( tagcount[tag] == undefined ) {
              tagcount[tag] = 1;
            } else {
              tagcount[tag]++;
            }
          }
        }
      }
    
      console.log(tagcount);
    
    });
    
    Login or Signup to reply.
  3. You can get the result you want with iterating over your data, I’ve taken your data like so as an example:

    var data = {
        "data": [{
            "tags": [
                "design",
                "development",
                "code",
                "foo",
                "bar"],
               "views": [
                "81"]
        }, {
            "tags": [
                "design",
                "foo",
                "photoshop",
                "alice",
                "bob"],
                "views": [
                "28"]
    
        }]
    };
    

    Then we can iterate over it like so:

    var countArray = [];
    $.each(data.data, function(dataKey, dataValue) {
        $.each(dataValue.tags, function(tagKey, tagValue) {
            if( !(tagValue in countArray) ) {
                countArray[tagValue] = 1;    
            } else {
                countArray[tagValue]++;
            }
        });
    });
    

    Console log would output

    console.log(countArray);
    
    [design: 2, development: 1, code: 1, foo: 2, bar: 1…]
    

    jsFiddle: http://jsfiddle.net/602puhja/

    Login or Signup to reply.
  4. var result = {};
    
    for(var i = 0; i < data.length; i++){
        for(var j = 0; j < data[i].tags.length; j++){
    
            var prop = data[i].tags[j];        
            result[prop] = !result[prop] ? 1 : result[prop] + 1;
        }
    }
    
    console.log(result);
    // Object {design: 2, development: 1, code: 1, foo: 2, bar: 1…}
    

    http://jsfiddle.net/v0rhxvff/

    Login or Signup to reply.
  5. You have to use a dictionary to count all the occurrences, then roll it in an array and sort it (if you want the same result as your output:

    // this will count per string each occurrence
    var occurrencies = {};
    
    function fetchAndSort(data) {
    
      var i,j;
    
      for (i = 0; i < data.data.length; i++) {
        var tags = data.data[i].tags;
        // now iterate inside tags
        for( j=0; j < tags.length; j++){
          // if there's not yet an entry in the dictionary, just create it
          if(!occurrencies[tags[j]]){
            occurrencies[tags[j]] = 0;
          }
          occurrencies[tags[j]]++;
        }
      }
    
      // at this point there's an object with all the keys and the relative count
      // if you want an ordered list you have to use an array because iterate on object
      // keys in JS [doesn't guarantee any order][1]
      var array = [];
      for( i in occurrencies ){
        array.push({name: i, count: occurrencies[i]});
      }
    
     // now sort it
     array.sort(function(entry1, entry2){
        // sort the array descending
        return entry2.count - entry1.count;
     });
    
     for( i = 0; i<array.length; i++){
       console.log(array[i].name + ':' + array.count);
     }
    
    };
    
    $.getJSON('myarray.json', fetchAndSort);
    

    The solution is a bit long due to explanation purposes. You can take this and optimise to your needs in case by shortening some bits.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search