When using LINQ-Group-By, the result is similar to a dictionary where the group item serves as the key and the element array is the object within a list.
Replicating this functionality in JavaScript is quite simple.
Here's the TypeScript code for reference:
// Source: https://stackoverflow.com/questions/20310369/declare-a-delegate-type-in-typescript
// type Predicate<T, TKey> = (item: T) => TKey;
interface Predicate<T, TKey>
{
(item: T): TKey;
}
function LinqGroupBy<TSource, TKey>(source: TSource[], keySelector: Predicate<TSource, TKey>)
: { [key: string]: TSource[] }
{
if (source == null)
throw new Error("ArgumentNullException: Source");
if (keySelector == null)
throw new Error("ArgumentNullException: keySelector");
let dict: { [key: string]: TSource[]} = {};
for (let i = 0; i < source.length; ++i)
{
let key: string = String(keySelector(source[i]));
if (!dict.hasOwnProperty(key))
{
dict[key] = [];
}
dict[key].push(source[i]);
}
return dict;
}
This TypeScript code can be transpiled down to:
function LinqGroupBy(source, keySelector)
{
if (source == null)
throw new Error("ArgumentNullException: Source");
if (keySelector == null)
throw new Error("ArgumentNullException: keySelector");
var dict = {};
for (var i = 0; i < source.length; ++i)
{
var key = String(keySelector(source[i]));
if (!dict.hasOwnProperty(key))
{
dict[key] = [];
}
dict[key].push(source[i]);
}
return dict;
}
Although the conversion to JavaScript may be a bit tricky given the nature of objects in the language, it generally functions effectively.