Skip to main content

Convert Array to String

convertArrayToString​

Joins elements of an array of primitive values or array of objects into a single string using a custom separator.

Import​

import { convertArrayToString } from 'nhb-toolbox';

Function Signatures​

function convertArrayToString<T extends Primitive>(
array: T[] | undefined,
options?: {
separator?: string;
}
): string;

Usage Examples​

convertArrayToString(['a', 'b', 'c']);
// "a, b, c"

API Reference​

Parameters​

NameTypeDescription
arrayT[]Array of primitives or objects to convert to string
optionsobjectOptions for separator and target key (if object array)
options.separatorstringOptional separator for joining values (default: ", ")
options.targetstringRequired if array contains objects. Dot-accessible key to extract primitive values only

Returns​

A string formed by joining the values (primitive or extracted) with the given separator.

Key Features​

  1. βœ… Supports Primitives and Objects: Handles both types cleanly with overloads.
  2. 🧩 Nested Key Extraction: Extracts deep object properties using dot notation like "user.name".
  3. 🧼 Handles Empty Inputs: Returns empty string if array is undefined or empty.
  4. πŸ› οΈ Customizable Separator: Use any string to separate values (e.g., " - ", "|", etc.).
  • Formatting tag or category lists for display.
  • Preparing data for tooltips, labels, logs, or CSV-like formats.
  • Joining object property values for human-readable summaries.

Notes​

  • This function always checks for array validity before processing.
  • For object arrays, use the target option to specify the key to extract (e.g., "user.name").
  • TypeScript enforces that the target path must resolve to a primitive value (like string, number, boolean, null, or undefined). In JavaScript, you may pass any path, but non-primitive values (e.g., objects, arrays) will result in [object Object] during stringification.
  • If you need to format, localize, or transform values before joining, consider mapping the array beforehand:
convertArrayToString(users.map(u => u.name.trim()), { separator: ' β€’ ' });

Limitations​

Requires a valid array. If not, it returns an empty string.

Warning
  • Does not auto-serialize objects. You must provide a target key when working with object arrays.
  • Only primitive values are supported correctly for both primitive arrays and object-based arrays.
  • Nested target keys must resolve to primitive values inside objects. TypeScript will error if you reference a non-primitive type.
  • There is no built-in formatting or filtering β€” the function joins raw values directly.

Aliases​

  • joinArrayElements – named export alias for convertArrayToString

Conclusion​

convertArrayToString makes joining arrays clean, type-safe, and flexibleβ€”perfect for tags, logs, tooltips, and more. Just supply your array and desired separator!