• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 112
  • Last Modified:

How do I return distinct values and their counts in an array?

I've got to write a function that returns distinct values in an array and their counts. So if my list of values is  is "1 3 5 3 7 3 1 1 5", then I need to return: "1(3) 3(3) 5(2) 7(1)"

How?
0
brucegust
Asked:
brucegust
1 Solution
 
leakim971PluritechnicianCommented:
Test page : http://jsfiddle.net/ELp6h/

var occurence = function(str,separator) {
    if(!separator) {
        separator = " ";
    }
    var arr = str.split(separator);
    var obj = {};
    for(var i=0;i<arr.length;i++) {
        var k = "" + arr[i];
        if(typeof obj[k] == "undefined") {
            obj[k] = 1;
        }
        else {
            obj[k]++;
        }
    }
    s = [];
    for(var j in obj) {
        s.push(j + "(" + obj[j] + ")");
    }
    return s.join(separator);
}

var input = "1 3 5 3 7 3 1 1 5";
var output = occurence( input );

//checking
alert( output );

Open in new window

0
 
Ioannis ParaskevopoulosCommented:
May i suggest using linq.js? This is a nice library for dealing with arrays etc.:

here is a sample code:
    var list = [1, 3, 5, 3, 7, 3, 1, 1, 5];
    var result = Enumerable.From(list)
    .GroupBy(
        function(x){
            return x
        },
        null,
        function(x,g){
            return {
                key:x,
                count:g.Count()
            }
        })
    .ToArray();

Open in new window


You may also check out this fiddle.

Giannis
0
 
brucegustAuthor Commented:
Had to go with pure JS and this worked!

Thanks!
0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now