Link to home
Start Free TrialLog in
Avatar of Bruce Gust
Bruce GustFlag for United States of America

asked on

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?
ASKER CERTIFIED SOLUTION
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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
Avatar of Bruce Gust

ASKER

Had to go with pure JS and this worked!

Thanks!