Results 1 to 5 of 5

Thread: Tally occurrences of a string in an array?

  1. #1
    Join Date
    Apr 2008
    Location
    San Diego, CA
    Posts
    352
    Thanks
    57
    Thanked 6 Times in 6 Posts

    Default Tally occurrences of a string in an array?

    Hi all,

    I have an alphabetically sorted array of names, like this:

    Code:
    var someArray = new Array("Bob", "Bob", "John", "Steve");
    I don't know what the names are going to be each time, and I want to output a list of the names with the number of occurrences next to the name, like this:

    Bob (2)
    John (1)
    Steve (1)


    Any tips greatly appreciated!
    Last edited by jlizarraga; 09-29-2008 at 12:45 AM. Reason: resolved

  2. #2
    Join Date
    Jun 2005
    Location
    英国
    Posts
    11,876
    Thanks
    1
    Thanked 180 Times in 172 Posts
    Blog Entries
    2

    Default

    Code:
    if (!Array.prototype.indexOf)
      Array.prototype.indexOf = function(elt /*, from*/) {
        var len = this.length,
            from = +arguments[1] || 0;
    
        from = (from < 0)
             ? Math.ceil(from)
             : Math.floor(from);
    
        if (from < 0)
          from += len;
    
        for (; from < len; ++from)
          if (from in this && this[from] === elt)
            return from;
    
        return -1;
      };
    
    Array.prototype.count = function(elt) {
      for (var r = 0, c = -1; (c = this.indexOf(elt, c + 1)) > -1; ++r);
      return r;
    };
    Twey | I understand English | 日本語が分かります | mi jimpe fi le jbobau | mi esperanton komprenas | je comprends français | entiendo español | tôi ít hiểu tiếng Việt | ich verstehe ein bisschen Deutsch | beware XHTML | common coding mistakes | tutorials | various stuff | argh PHP!

  3. The Following User Says Thank You to Twey For This Useful Post:

    jlizarraga (09-29-2008)

  4. #3
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    But how could we use that? Perhaps:

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    
    <style type="text/css">
    #result {
    font: normal 90% sans-serif;
    }
    </style>
    
    <script type="text/javascript">
    if (!Array.prototype.indexOf)
      Array.prototype.indexOf = function(elt /*, from*/) {
        var len = this.length,
            from = +arguments[1] || 0;
    
        from = (from < 0)
             ? Math.ceil(from)
             : Math.floor(from);
    
        if (from < 0)
          from += len;
    
        for (; from < len; ++from)
          if (from in this && this[from] === elt)
            return from;
    
        return -1;
      };
    
    Array.prototype.count = function(elt) {
      for (var r = 0, c = -1; (c = this.indexOf(elt, c + 1)) > -1; ++r);
      return r;
    };
    
    Array.prototype.removeDuplicates = function (deep) {
      deep = deep || 0; var is = function(i){return i? i : i === 0?  '0' : false;};
      for(var i = 0; i < this.length; ++i)
        for(var j = this.length-1; j > i; --j)
          if((is(this[i][deep]) || this[i]) == (is(this[j][deep]) || this[j]))
            this.splice(j, 1);
    };
    
    
    Array.prototype.enumerateEntries = function () {
     for(var c = [], i = 0; i < this.length; ++i)
      c.push(this[i] + ' (' + this.count(this[i]) + ')');
     c.removeDuplicates();
     return c;
    };
    
    var someArray = new Array("Bob", "Bob", "John", "Steve");
    
    window.onload = function(){
    document.getElementById('result').appendChild(document.createTextNode(someArray.enumerateEntries().join('\x0a\x0d')));
    };
    </script>
    </head>
    <body>
    <div>
    <pre id="result"></pre>
    </div>
    </body>
    </html>
    Last edited by jscheuer1; 09-28-2008 at 10:57 AM.
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  5. #4
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    But a much simpler approach to getting the data would be:

    Code:
    Array.prototype.enumerate = function(){
    for(var o = {}, i = 0; i < this.length; ++i)
    o[this[i]] = o[this[i]]? ++o[this[i]] : 1;
    return o;
    };
    Which could be formatted more or less as before, or using this more elaborate and better looking method:

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    <style type="text/css">
    #result {
    font: normal 90% sans-serif;
    }
    #result .rhspan {
    float: right;
    }
    #result br {
    clear: right;
    }
    </style>
    <script type="text/javascript">
    Array.prototype.enumerate = function(){
    for(var o = {}, i = 0; i < this.length; ++i)
    o[this[i]] = o[this[i]]? ++o[this[i]] : 1;
    return o;
    };
    
    function displayResults(ar, el){
    el = document.getElementById(el);
    while (el.lastChild) el.removeChild(el.lastChild);
    var o = ar.enumerate(), p, s0, s1, br, w = 0;
    for (p in o){
    w = Math.max( w, (p + o[p]).length + 3 );
    s0 = document.createElement('span');
    s1 = document.createElement('span');
    br = document.createElement('br');
    s1.className = 'rhspan';
    s0.appendChild(document.createTextNode(p));
    s1.appendChild(document.createTextNode('(' + o[p] + ')'));
    el.appendChild(s1);
    el.appendChild(s0);
    el.appendChild(br);
    };
    el.style.width = w + 'ex';
    };
    
    var someArray = new Array("Bob", "Twey", "Bob", "Twey", "John", "Mary", "Steve", "Mary", "Twey", "A real long name here", 0, 0, 257);
    </script>
    </head>
    <body>
    <div>
    <input type="button" value="Go!" onclick="displayResults(someArray, 'result');">
    <div id="result">
    Results Will Appear Here
    </div>
    </div>
    </body>
    </html>
    Last edited by jscheuer1; 09-28-2008 at 06:01 PM. Reason: simplify display function - add to array to demonstrate items that can be handled
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  6. The Following User Says Thank You to jscheuer1 For This Useful Post:

    jlizarraga (09-29-2008)

  7. #5
    Join Date
    Apr 2008
    Location
    San Diego, CA
    Posts
    352
    Thanks
    57
    Thanked 6 Times in 6 Posts

    Default

    Thank you both, this is exactly what I needed.

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •