Collections
Object and array manipulation utilities.
objectFilter
Filters an object's entries by a predicate, returning a new object with only matching keys.
import { objectFilter } from '@repo/utils'
function objectFilter<T>(
obj: Record<string, T>,
predicate: (value: T, key: string) => boolean
): Record<string, T>
Example
import { objectFilter } from '@repo/utils'
const data = { a: 1, b: 2, c: 3, d: 4 }
objectFilter(data, (value) => value > 2)
// { c: 3, d: 4 }
objectFilter(data, (_, key) => key !== 'b')
// { a: 1, c: 3, d: 4 }
objectMap
Maps over an object's values, returning a new object with the same keys and transformed values.
import { objectMap } from '@repo/utils'
function objectMap<T, R>(
obj: Record<string, T>,
mapper: (value: T, key: string) => R
): Record<string, R>
Example
import { objectMap } from '@repo/utils'
const prices = { apple: 1.5, banana: 0.75, cherry: 3.0 }
objectMap(prices, (price) => price * 2)
// { apple: 3, banana: 1.5, cherry: 6 }
objectMap(prices, (price, key) => `${key}: $${price}`)
// { apple: 'apple: $1.5', banana: 'banana: $0.75', cherry: 'cherry: $3' }
mergeTwoDimensionalObjects
Merges two objects whose values are arrays. Shared keys have their arrays concatenated; unique keys are preserved.
import { mergeTwoDimensionalObjects } from '@repo/utils'
function mergeTwoDimensionalObjects<
T extends Record<string, any[] | undefined>,
K extends Record<string, any[] | undefined>
>(value1: T, value2: K): T & K
Example
import { mergeTwoDimensionalObjects } from '@repo/utils'
const obj1 = { a: [1, 2], b: [3, 4] }
const obj2 = { a: [5, 6], c: [7, 8] }
mergeTwoDimensionalObjects(obj1, obj2)
// { a: [1, 2, 5, 6], b: [3, 4], c: [7, 8] }
chunkArray
Splits an array into chunks of a specified size.
import { chunkArray } from '@repo/utils'
function chunkArray<T>(array: T[], size: number): T[][]
Example
import { chunkArray } from '@repo/utils'
chunkArray([1, 2, 3, 4, 5], 2)
// [[1, 2], [3, 4], [5]]
chunkArray(['a', 'b', 'c', 'd'], 3)
// [['a', 'b', 'c'], ['d']]
getValueByPath
Gets a value from a nested object using a dot-separated path string. Supports array index access.
import { getValueByPath } from '@repo/utils'
function getValueByPath<T>(
obj: T[] | Record<string, T>,
path: string
): T | undefined
Example
import { getValueByPath } from '@repo/utils'
const data = { user: { profile: { name: 'John' } } }
getValueByPath(data, 'user.profile.name')
// 'John'
getValueByPath(data, 'user.profile.age')
// undefined
// Array index access
const list = { items: [{ id: 1 }, { id: 2 }] }
getValueByPath(list, 'items.0.id')
// 1