Array helpers for TypeScript that you keep writing by hand β filter nulls with real type narrowing, toggle and upsert objects by key, deduplicate. No lodash needed.
- Tiny. 418 bytes (minified and brotli). Zero dependencies.
- Typed.
filterNullableactually narrows the return type β no more(T | null)[]. - Immutable. Every function returns a new array, safe to use directly in React
setState. - Fills the gap. The specific helpers lodash skips:
upsertByKey,toggleByKey,filterNullable.
npm i array-utils-tsimport {
filterNullable,
filterEmpty,
hasEmpty,
uniq,
isUniq,
toggleItem,
updateByKey,
upsertByKey,
toggleByKey,
isFirstByKey,
isLastByKey,
enumerate,
} from "array-utils-ts"filterNullable β removes null and undefined, narrows the return type
filterNullable([1, null, 2, undefined]) // β [1, 2] (typed as number[])filterEmpty β also removes empty strings ""
filterEmpty([1, null, 2, undefined, 3, "", "a"]) // β [1, 2, 3, "a"]hasEmpty β returns true if any element is null, undefined, or ""
hasEmpty(["a", "b", "c"]) // β false
hasEmpty(["a", "", "c"]) // β true
hasEmpty(["a", undefined, "c"]) // β trueuniq β removes duplicates
uniq([1, 2, 1, 3]) // β [1, 2, 3]isUniq β checks if all elements are unique
isUniq([1, 2, 3]) // β true
isUniq([1, 2, 1]) // β falsetoggleItem β adds an item if missing, removes it if present; useful in multi-select UI
toggleItem([1, 2, 3], 4) // β [1, 2, 3, 4]
toggleItem([1, 2, 3], 3) // β [1, 2]updateByKey β updates a matching object; returns the same reference if not found
const arr = [
{ id: 1, v: 1 },
{ id: 2, v: 1 },
]
updateByKey(arr, "id", { id: 1, v: 2 }) // β [{ id: 1, v: 2 }, { id: 2, v: 1 }]
updateByKey(arr, "id", { id: 3, v: 1 }) // β arr (same reference, not found)upsertByKey β updates if found, appends if not
const arr = [
{ id: 1, v: 1 },
{ id: 2, v: 1 },
]
upsertByKey(arr, "id", { id: 1, v: 2 }) // β [{ id: 1, v: 2 }, { id: 2, v: 1 }]
upsertByKey(arr, "id", { id: 3, v: 1 }) // β [...arr, { id: 3, v: 1 }]toggleByKey β removes an object if its key matches, appends it if not
const arr = [
{ id: 1, v: 1 },
{ id: 2, v: 1 },
]
toggleByKey(arr, "id", { id: 1, v: 2 }) // β [{ id: 2, v: 1 }]
toggleByKey(arr, "id", { id: 3, v: 1 }) // β [...arr, { id: 3, v: 1 }]isFirstByKey / isLastByKey β check an object's position in the array
const arr = [{ id: 1 }, { id: 2 }, { id: 3 }]
isFirstByKey(arr, "id", { id: 1 }) // β true
isFirstByKey(arr, "id", { id: 3 }) // β false
isLastByKey(arr, "id", { id: 3 }) // β true
isLastByKey(arr, "id", { id: 1 }) // β falseenumerate β pairs each element with its index, like Python's enumerate()
const arr = ["a", "b", "c"]
enumerate(arr) // β [[0, "a"], [1, "b"], [2, "c"]]
enumerate(arr, 1) // β [[1, "a"], [2, "b"], [3, "c"]]