Skip to main content

@rtorcato/js-common / arrays

arrays

Array Utilities

unique()

unique<T>(arr): T[]

Defined in: arrays/index.ts:16

Removes duplicate values from an array while preserving order. Uses Set for O(n) performance with primitive values.

Example

unique([1, 2, 2, 3, 1]) // [1, 2, 3]
unique(['a', 'b', 'a']) // ['a', 'b']
unique([{id: 1}, {id: 2}, {id: 1}]) // [{id: 1}, {id: 2}, {id: 1}] (objects by reference)

Type Parameters

T

T

Parameters

arr

T[]

The array to remove duplicates from

Returns

T[]

A new array with unique values


chunk()

chunk<T>(arr, size): T[][]

Defined in: arrays/index.ts:37

Chunks an array into smaller arrays of a specified size. The last chunk may be smaller if the array length is not evenly divisible.

Example

chunk([1, 2, 3, 4, 5], 2) // [[1, 2], [3, 4], [5]]
chunk(['a', 'b', 'c'], 2) // [['a', 'b'], ['c']]
chunk([1, 2, 3], 5) // [[1, 2, 3]]

Type Parameters

T

T

Parameters

arr

T[]

The array to chunk

size

number

The size of each chunk (must be positive)

Returns

T[][]

An array of chunks

Throws

When size is less than 1


compact()

compact<T>(arr): T[]

Defined in: arrays/index.ts:61

Removes all falsy values from an array. Falsy values: false, 0, -0, 0n, "", null, undefined, NaN

Example

compact([0, 1, false, 2, '', 3, null, undefined, NaN]) // [1, 2, 3]
compact(['', 'hello', 0, 'world']) // ['hello', 'world']
compact([true, false, 1, 0]) // [true, 1]

Type Parameters

T

T

Parameters

arr

T[]

The array to filter

Returns

T[]

A new array with only truthy values


shuffle()

shuffle<T>(arr): T[]

Defined in: arrays/index.ts:84

Shuffles an array using the Fisher-Yates algorithm. Returns a new array without modifying the original.

Example

shuffle([1, 2, 3, 4, 5]) // [3, 1, 5, 2, 4] (random order)
shuffle(['a', 'b', 'c']) // ['c', 'a', 'b'] (random order)

// Original array is unchanged
const original = [1, 2, 3]
const shuffled = shuffle(original)
console.log(original) // [1, 2, 3]

Type Parameters

T

T

Parameters

arr

T[]

The array to shuffle

Returns

T[]

A new shuffled array