Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

Map.groupBy

Groups elements into a Map by any key.

Available since: ES2024

Syntax

Map.groupBy(items, callbackFn)

Parameters

ParameterTypeDescription
itemsIterableAn array or another iterable.
callbackFnFunctionA function that returns the group key for an element.

Return value

MapA Map in which each key maps to an array of the group's elements.

Examples

Grouping by a numeric key:

const words = ['hi', 'cat', 'yo', 'dog', 'horse'];
const byLength = Map.groupBy(words, (word) => word.length);
 
console.log(byLength.get(2).join(', '));
console.log(byLength.get(3).join(', '));
console.log([...byLength.keys()].join(', '));

Output:

hi, yo
cat, dog
2, 3, 5

Notes

The difference from Object.groupBy(): keys are not converted to strings, so they can be numbers, objects or any other values.

See also

  • Object.groupBy — Groups the elements of an array by a key.
  • Map — A collection of key–value pairs where a key can be anything.

Related recipes

In the tutorial

  • Map and Set — The Map and Set collections in JavaScript: a dictionary with keys of any type and a set of unique values.

Thanks for reading!

Donate to the site — we work hard for you.