Skip to main content
This release is 5 versions behind 1.33.0 — the latest version of @es-toolkit/es-toolkit. Jump to latest

@es-toolkit/es-toolkit@1.29.0-dev.958+1d1d0ee6
Built and signed on GitHub Actions

A modern JavaScript utility library that's 2-3 times faster and up to 97% smaller—a major upgrade to lodash.

This package works with Cloudflare Workers, Node.js, Deno, Bun, Browsers
This package works with Cloudflare Workers
This package works with Node.js
This package works with Deno
This package works with Bun
This package works with Browsers
JSR Score
100%
Published
3 months ago (1.29.0-dev.958+1d1d0ee6)
function groupBy
groupBy<
T,
K extends PropertyKey,
>
(
arr: readonly T[],
getKeyFromItem: (item: T) => K,
): Record<K, T[]>

Groups the elements of an array based on a provided key-generating function.

This function takes an array and a function that generates a key from each element. It returns an object where the keys are the generated keys and the values are arrays of elements that share the same key.

Examples

Example 1

const array = [ { category: 'fruit', name: 'apple' }, { category: 'fruit', name: 'banana' }, { category: 'vegetable', name: 'carrot' } ]; const result = groupBy(array, item => item.category); // result will be: // { // fruit: [ // { category: 'fruit', name: 'apple' }, // { category: 'fruit', name: 'banana' } // ], // vegetable: [ // { category: 'vegetable', name: 'carrot' } // ] // }

Type Parameters

  • The type of elements in the array.
K extends PropertyKey
  • The type of keys.

Parameters

arr: readonly T[]
  • The array to group.
getKeyFromItem: (item: T) => K
  • A function that generates a key from an element.

Return Type

Record<K, T[]>

An object where each key is associated with an array of elements that share that key.

Add Package

deno add jsr:@es-toolkit/es-toolkit

Import symbol

import { groupBy } from "@es-toolkit/es-toolkit";

---- OR ----

Import directly with a jsr specifier

import { groupBy } from "jsr:@es-toolkit/es-toolkit";

Add Package

npx jsr add @es-toolkit/es-toolkit

Import symbol

import { groupBy } from "@es-toolkit/es-toolkit";

Add Package

yarn dlx jsr add @es-toolkit/es-toolkit

Import symbol

import { groupBy } from "@es-toolkit/es-toolkit";

Add Package

pnpm dlx jsr add @es-toolkit/es-toolkit

Import symbol

import { groupBy } from "@es-toolkit/es-toolkit";

Add Package

bunx jsr add @es-toolkit/es-toolkit

Import symbol

import { groupBy } from "@es-toolkit/es-toolkit";