JavaScript Map.groupBy()

Beginner
5 min read
Updated: Nov 2026
3 examples
Map

Definition

Map.groupBy(items, callbackFn) walks through items, calls callbackFn(item, index) for each one, and puts that item into an array under the returned key. The result is a new Map. Keys that never appear get no entry. It is a static helper on Map (not called on an instance), newer in the language, and not in every engine yet: check before use.

Remember
Map.groupBy(items, callbackFn)  → a new Map

callback returns key "a"  → item goes into map.get("a") array
key never returned        → no entry for that key
input list                → not changed

Syntax

Call Map.groupBy with a list and a function that picks a key for each item.

JavaScript
Map.groupBy(items, callbackFn)
CallWhat it does
Map.groupBy(items, callbackFn)Group every item under the key returned by callbackFn(item, index).
typeof Map.groupBy === "function"Feature check. Run it before relying on the method.

Static method (ES2024). Call it on Map, not on a Map instance. Each example starts with a short fallback for engines that lack it.

Library declarations
JavaScript
Map.groupBy(items, callbackFn)   // returns a new Map

// items: iterable (array, Set, ...)
// callbackFn(item, index): returns the group key

Parameters

ParameterDescription
itemsRequired. Any iterable of values to group, such as an array.
callbackFnRequired. Called as callbackFn(item, index). Its return value becomes the Map key for that item's group.

Return Value

Return ValueDescription
MapA new Map from each group key to an array of items. The input list is not changed.

JavaScript Examples

Example 1 — Group Numbers by Even or Odd

Split a list of numbers into two groups with a simple key.

JavaScript
// Fills in Map.groupBy only on engines that lack it.
if (!Map.groupBy) {
  Map.groupBy = function (items, callbackFn) {
    var map = new Map();
    var i = 0;
    for (var item of items) {
      var key = callbackFn(item, i++);
      if (!map.has(key)) map.set(key, []);
      map.get(key).push(item);
    }
    return map;
  };
}

const nums = [1, 2, 3, 4, 5, 6];
const groups = Map.groupBy(nums, function (n) {
  return n % 2 === 0 ? "even" : "odd";
});

console.log(JSON.stringify(groups.get("even")));  // [2,4,6]
console.log(JSON.stringify(groups.get("odd")));   // [1,3,5]
console.log(groups.size);                         // 2
Try It Yourself

How It Works

  1. Each number gets a key. The callback returns "even" or "odd" for every item.
  2. Items land in arrays. get("even") and get("odd") are arrays of the matching numbers.
  3. Only used keys exist. The Map size is 2 because those two keys were returned.

Example 2 — Group Objects by a Property

Group people by their team name.

JavaScript
// Fills in Map.groupBy only on engines that lack it.
if (!Map.groupBy) {
  Map.groupBy = function (items, callbackFn) {
    var map = new Map();
    var i = 0;
    for (var item of items) {
      var key = callbackFn(item, i++);
      if (!map.has(key)) map.set(key, []);
      map.get(key).push(item);
    }
    return map;
  };
}

const people = [
  { name: "Ann", team: "red" },
  { name: "Bob", team: "blue" },
  { name: "Cia", team: "red" }
];

const byTeam = Map.groupBy(people, function (p) {
  return p.team;
});

console.log(byTeam.get("red").map(function (p) { return p.name; }).join(","));  // Ann,Cia
console.log(byTeam.get("blue")[0].name);                                        // Bob
console.log(byTeam.has("green"));                                               // false
Try It Yourself

How It Works

  1. The property becomes the key. Returning p.team groups everyone with the same team together.
  2. Each value is an array of objects. get("red") holds Ann and Cia; get("blue") holds Bob.
  3. Unused keys are absent. has("green") is false because nobody had that team.

Example 3 — Empty Groups Are Not Created

Only keys that the callback actually returns appear in the Map.

JavaScript
// Fills in Map.groupBy only on engines that lack it.
if (!Map.groupBy) {
  Map.groupBy = function (items, callbackFn) {
    var map = new Map();
    var i = 0;
    for (var item of items) {
      var key = callbackFn(item, i++);
      if (!map.has(key)) map.set(key, []);
      map.get(key).push(item);
    }
    return map;
  };
}

const words = ["hi", "hey", "yo"];
const byLen = Map.groupBy(words, function (w) {
  return w.length;
});

console.log(JSON.stringify(byLen.get(2)));   // ["hi","yo"]
console.log(JSON.stringify(byLen.get(3)));   // ["hey"]
console.log(String(byLen.get(4)));           // undefined
console.log(byLen.size);                     // 2
Try It Yourself

How It Works

  1. Lengths 2 and 3 appear. Those lengths were returned for real words, so both keys exist.
  2. Length 4 does not. No word had length 4, so get(4) is undefined.
  3. Size matches used keys. The Map size is 2, not a full range of possible lengths.

Browser & Runtime Support

Map.groupBy() is a newer static helper (ES2024). Not every engine has it yet.

✓ Newer · ES2024

Map.groupBy()

Supported in current browsers and recent runtimes. Older engines need a check or the fallback in each example.

Newer Not in every engine yet
Google Chrome Chrome 148 has it (tested)
Newer
Mozilla Firefox Newer versions only
Check support
Apple Safari Newer versions only
Check support
Microsoft Edge Newer versions only
Check support
Node.js Not in Node 24.15 (tested)
Not available
Deno Newer versions only
Check support
Map.groupBy() Check support

Bottom line: Detect it with typeof Map.groupBy === "function", or use the fallback shown in each example.

Frequently Asked Questions

It walks a list, asks your function for a key for each item, and returns a new Map from those keys to arrays of items.
No. It is static: call Map.groupBy(items, fn), not map.groupBy(...).
No. It builds a new Map. The original list stays the same.
A key appears only if the callback returned it at least once. Empty groups are never created.
No. It is newer (ES2024). Check typeof Map.groupBy === "function" before you rely on it.

Back to the Map Method Index

Loop over the key/value pairs inside a Map you already built.

Map methods →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

11 people found this page helpful