---
title: "Group JavaScript objects by property in C# with Object.groupBy"
url: https://recursiveai.org/oneecma/cookbook/group-javascript-records-by-property/
description: "Group a JavaScript array of objects by a category property with Object.groupBy, then return both buckets and print their counts from C#."
version: "1.1.1"
---

# 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.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneEcma) · [GitHub](https://github.com/recursive-ai-oss/oneecma-csharp) · [Docs](https://recursiveai.org/oneecma/docs/) · [Download example (.zip)](https://recursiveai.org/oneecma/cookbook/group-javascript-records-by-property/group-javascript-records-by-property.zip)

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

```shell
dotnet add package RecursiveAI.OneEcma
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

```csharp
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](https://recursiveai.org/oneecma/cookbook/group-javascript-records-by-property/group-javascript-records-by-property.zip), then `dotnet run`.

```csharp
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
```

## Related recipes

- [Run a JavaScript function from C#](https://recursiveai.org/oneecma/cookbook/call-javascript-function/)
- [Combine JavaScript sets](https://recursiveai.org/oneecma/cookbook/combine-javascript-sets/)

## 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](https://262.ecma-international.org/15.0/#sec-object.groupby), 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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/groupBy) 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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/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.
