Skip to main content

Convert Array to String

Joins elements of an array into a single string, using a custom separator.

Import

import { convertArrayToString } from 'nhb-toolbox';

Function Signature

function convertArrayToString<T>(array: T[],  separator?: string): string

Usage Examples

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

API Reference

Parameters

NameTypeDescription
arrayT[]Array to convert to a string
separatorstringOptional. Separator for elements (default: ",")

Returns

A string of array elements joined by the specified separator.

Key Features

  1. Custom Separator: Use any string as a separator (comma, dash, pipe, etc.).
  2. Type Support: Works with any array element type (stringified as needed).
  3. Simple API: One line for most use cases.
  4. Handles Empty Array: Returns an empty string for empty input arrays.

Limitations

  1. Invalid Input: Throws an error if the input is not a valid array.
  2. No Deep Serialization: Elements are joined using their string representation. Objects will become "[object Object]" unless you stringify them manually.
  3. No Filtering: Does not remove falsy or empty values automatically.

Notes

  • Always ensure the input is a valid array.
  • If array elements are objects, consider array.map(obj => JSON.stringify(obj)) before passing to this function.
  • Building display strings from lists (tags, categories, items, etc.).
  • Exporting arrays to CSV-like formats or quick string storage.
  • Creating readable strings for logging, tooltips, or input fields.

Conclusion:
convertArrayToString makes joining arrays readable, flexible, and easy—perfect for tags, logs, labels, and more. Just supply your array and desired separator!