Array/Since
1.38.0groupBy
Groups array elements into an object using the value of a specified object property as the group key.
groupBy(array, key):Record<string, T[]>Parameters
arrayT[]requiredThe array of objects whose elements should be grouped.
keyKrequiredThe property key whose value is used to determine the group for each element.
Returns
Record<string, T[]>An object where each property represents a group and contains the array elements belonging to that group.
Examples
01
Basic usage
Group objects by the value of the specified property.
TypeScript
import { groupBy } from "@cyref/js";
const users = [
{ name: "Amir", role: "developer" },
{ name: "Sara", role: "designer" },
{ name: "Reza", role: "developer" },
];
const result = groupBy(users, "role");
console.log(result);
// {
// developer: [
// { name: "Amir", role: "developer" },
// { name: "Reza", role: "developer" },
// ],
// designer: [
// { name: "Sara", role: "designer" },
// ],
// }02
Group by category
The key can be any property key available on the object type.
TypeScript
import { groupBy } from "@cyref/js";
const products = [
{ name: "Laptop", category: "electronics" },
{ name: "Phone", category: "electronics" },
{ name: "T-Shirt", category: "clothing" },
];
const result = groupBy(products, "category");
console.log(result);
// {
// electronics: [
// { name: "Laptop", category: "electronics" },
// { name: "Phone", category: "electronics" },
// ],
// clothing: [
// { name: "T-Shirt", category: "clothing" },
// ],
// }03
Single-item groups
Values that occur only once create groups containing a single element.
TypeScript
import { groupBy } from "@cyref/js";
const items = [
{ id: 1, type: "a" },
{ id: 2, type: "b" },
{ id: 3, type: "a" },
];
const result = groupBy(items, "type");
console.log(result);
// {
// a: [
// { id: 1, type: "a" },
// { id: 3, type: "a" },
// ],
// b: [
// { id: 2, type: "b" },
// ],
// }04
Empty array
An empty input array produces an empty object.
TypeScript
import { groupBy } from "@cyref/js";
const result = groupBy([], "type");
console.log(result);
// {}Built with@cyref/js·Official documentation