Recursive AI

Group JavaScript objects by property in C# with Object.groupBy

OneEcma is a free, open-source JavaScript interpreter for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

Object.groupBy puts records with the same category into the same array.

Terminal
dotnet add package RecursiveAI.OneEcma

Requires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.

C#
using RecursiveAI.OneEcma;
 
var engine = new ScriptEngine();
Console.WriteLine(engine.Evaluate("""
    const items = [
      { category: 'drinks' },
      { category: 'food' },
      { category: 'drinks' }
    ];
    const groups = Object.groupBy(
      items, item => item.category);
    `drinks: ${groups.drinks.length}\n` +
      `food: ${groups.food.length}`;
    """).AsString);
Text
drinks: 2
food: 1

The full program

The downloadable program keeps the item names in its two buckets, returns both arrays as JSON, and counts their entries in C# without hard-coding the categories.

Unzip the example, then dotnet run.

C#
using RecursiveAI.OneEcma;
 
var engine = new ScriptEngine();
var result = engine.Evaluate("""
    const items = [
      { name: 'Tea', category: 'drinks' },
      { name: 'Bread', category: 'food' },
      { name: 'Juice', category: 'drinks' }
    ];
    const groups = Object.groupBy(
      items, item => item.category);
    JSON.stringify(groups);
    """);
using var json = System.Text.Json.JsonDocument
    .Parse(result.AsString);
foreach (var group in json.RootElement.EnumerateObject())
{
    var count = group.Value.GetArrayLength();
    Console.WriteLine($"{group.Name}: {count}");
}

dotnet run prints:

Text
drinks: 2
food: 1

If the callback throws, grouping stops and the exception propagates; it doesn’t return partial groups.

Variations

Use Map.groupBy when a number and its string spelling must remain separate keys. Replace the JavaScript passed to Evaluate with this script and print the returned .AsString:

JAVASCRIPT
const items = [{ category: 7 }, { category: '7' }];
const groups = Map.groupBy(items, item => item.category);
'number: ' + groups.get(7).length + '\n' +
  'string: ' + groups.get('7').length;
Text
number: 1
string: 1

The short answer

Call Object.groupBy(items, item => item.category) to group a JavaScript array of objects by its category property. The result has one property per distinct category, with an array of the original records as each value. Read a group’s length for its count. In the full example, JavaScript returns both buckets as JSON and C# prints the counts without knowing the keys ahead of time.

How does Object.groupBy group an array of objects by property?

Object.groupBy was added in ES2024, and the JavaScript inside Evaluate also runs in current versions of Node.js and major browsers.

The callback runs for each item and returns a key, not the item to store. Returning item.category from a record named Tea files the entire record under drinks, including its name. Objects in each bucket stay in input order. As MDN’s Object.groupBy reference explains, the grouping operation does not clone the input objects. If the input records are changed afterward, their fields can change in the buckets, but group membership is not recomputed.

Object.groupBy returns an object with no prototype. That doesn’t prevent property lookup or JSON serialization for these string keys, but the result doesn’t inherit methods such as hasOwnProperty. If the array has no records for a category, that key won’t exist; it doesn’t get an empty bucket automatically.

What’s the difference between Object.groupBy and Map.groupBy?

Use Object.groupBy when the callback returns names such as drinks and you want properties that can go straight into a JSON object. Its keys are property keys, so a number such as 7 becomes the string "7". JavaScript symbols are also valid object property keys, but they aren’t represented in JSON. Use Map.groupBy when you need numbers to stay numbers or need to group by object identity. Read a map bucket with .get(key), not bracket lookup. If you’re sending map buckets to C#, decide how to represent the keys before serializing; the map itself is not a JSON object of those entries.

All oneecma recipes