Skip to content

ensureArray

Wraps a value in an array if it is not already one. If the value is already an array, it is returned as-is. If the value is null or undefined, returns an empty array. When a depth is specified, the resulting array is flattened to that depth (like Array.prototype.flat(depth)).

Available since v2.0.0

import { ensureArray } from '@helpers4/array';
// or, from the all-in-one package (same code, one install):
import { ensureArray } from 'helpers4/array';
ensureArray<T>(value: T | readonly T[] | null | undefined): T[]
ParameterTypeDescription
valueT | readonly T[] | null | undefinedThe value to ensure is an array

T[] — The value wrapped in an array, or the value itself if already an array

Wraps a non-array value in an array.

ensureArray('hello')
// => ['hello']

Returns the array as-is if already an array.

ensureArray([1, 2, 3])
// => [1, 2, 3]

Returns an empty array for null or undefined values.

ensureArray(null)
// => []

Flattens the resulting array to a given depth, like Array.prototype.flat().

ensureArray([[1, [2, 3]], [4]], 1)
// => [1, [2, 3], 4]

View source on GitHub