6
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 don’t know an efficient way to implement this.
I created a jsPerf test here with linq.js and a method I’ve created that doesn’t use a comparer, so this only works on 'normal' types'. (Testing of these methods here)
Other libraries like underscore and Lo-Dash does not have the parameter comparer then their implementation is not relevant.
The key of each group can be up to a class, need a comparer to know if the key value is equal between objects.
Basically I’m trying to copy C# Linq GroupBy documented here.
Input example:
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 that):
[
{
"Key": {"Value":10},
"Elements":["Foo","Bar"]
},
{
"Key": {"Value":20},
"Elements":["Foo","Bar"]
}
]
Any idea how to implement this?
Let me get this straight, you want to compare if keySelector (which is equal to the id of an element) is equal to elementSelector (which is the name of another element)?
– Kenny Rafael
I’m basically trying to copy the
GroupByofc#http://msdn.microsoft.com/en-us/library/bb534304(v=vs.110). aspx .keySelectoris what will extract the key from an object to be the key to the group.elementSelectoris what will extract the object to be placed in the list of group elements.– BrunoLM
So you want to create an associative array, that’s it?
– Kenny Rafael
@Kennyrafael The group by does this,
var arr= [{ Chave: 1, Valor: 2}, { Chave: 1, Valor: 3}]... Grouping the result is[{ Key: 1, Elements: [2,3] }]. It could also be an assosiative array...{ 1: [2,3] }...– BrunoLM