I'm trying to implement a GroupBy
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 do not know an efficient way to implement this.
I created a test in jsPerf here with linq.js
and a method I created that does not use a comparer
, so this only works on 'normal' types. ( Test these methods here )
Other libraries such as underscore
and Lo-Dash
do not have the comparer
parameter so their implementation is not relevant.
The key of each group can be up to one class, I need a comparer
to know if the key value is equal between objects.
I'm basically trying to copy the C # Linq GroupBy
documented here .
Example input:
var arrComplex =
[
{ N: { Value: 10 }, Name: "Foo" },
{ N: { Value: 10 }, Name: "Bar" },
{ N: { Value: 20 }, Name: "Foo" },
{ N: { Value: 20 }, Name: "Bar" }
];
Output example (or something like this):
[
{
"Key": {"Value":10},
"Elements":["Foo","Bar"]
},
{
"Key": {"Value":20},
"Elements":["Foo","Bar"]
}
]
Any ideas how to implement this?