---
title: "Normalize an array of objects by a given key"
description: "Transform a collection of objects into an object indexed by a specific key in TypeScript."
date: "2025-10-02"
tags: ["typescript","array","normalization","frontend"]
canonical: "/snippets/typescript/array/collection-key-by"
---

import { Code } from '@astrojs/starlight/components'
import Source from './collection-key-by.ts?raw'

## Normalize an array of objects (or collection) by a given key

The keyBy and collectionKeyBy functions can be useful in several scenarios where you need to transform a collection of objects into an object for easier access (With time complexity: **O(1)**) or manipulation.

1. **Data Normalization**: When you're working with a large dataset, it's often more efficient to store the data in a normalized form. For example, if you have an array of users, you might want to transform it into an object where the keys are user IDs and the values are the user objects. This allows you to quickly and easily look up a user by their ID.

2. **Data Indexing**: Similarly, if you're working with a collection of objects that have a unique identifier (like a database ID), you can use these functions to create an index of the objects by their identifier. This can significantly speed up operations like searching for an object by its identifier.

3. **Data Aggregation**: If you need to aggregate data based on a certain property, these functions can help. For example, if you have an array of transactions and you want to group them by user ID, you can use keyBy to create an object where the keys are user IDs and the values are arrays of transactions for each user.

<Code code={Source} lang="ts" title="collection-key-by.ts" wrap />
