What is the most efficient way to implement GroupBy in Javascript?

Viewed 2392

I am trying to implement a GroupBy method with these parameters

function GroupBy(keySelector, elementSelector, comparer)
{
    // keySelector = function(e) { return e.ID }
    // elementSelector = function(e) { return e.Name }
    // comparer = { Equals: function(a,b) { return a==b }, GetHashCode:... }
}

However I don't know an efficient way to implement it.

I created a jsPerf test with linq.js and a method I created which doesn't use a comparer and only work on flat types. (Output test here)

Other libraries such as underscore and Lo-Dash doesn't take a comparer parameter. So their implementations are irrelevant.

My key could be a class, so I need something to determine if TKey is the same in different instances.

So basically what I am trying to do is copy C# Linq GroupBy behavior documented here.

Sample input:

var arrComplex =
[
    { N: { Value: 10 }, Name: "Foo" },
    { N: { Value: 10 }, Name: "Bar" },
    { N: { Value: 20 }, Name: "Foo" },
    { N: { Value: 20 }, Name: "Bar" }
];

Sample output (or something like this):

[
    {
       "Key": {"Value":10},
       "Elements":["Foo","Bar"]
    },
    {
        "Key": {"Value":20},
        "Elements":["Foo","Bar"]
    }
] 

Any ideas on how to implement it?

Bounty

For the bounty I would like you take in consideration that:

  • The key could be an object
  • Two objects can be equal if some property is equal
  • It should be as fast as or faster than existing solutions
  • The result can be an array or object, doesn't matter as long as I can get elements grouped by a key

Well, I expect a complete answer.

2 Answers
Related