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
- Default Separator
- Custom Separator
- Pipe Separator
- Empty Array
convertArrayToString(['a', 'b', 'c']);
// Returns: "a,b,c"
convertArrayToString([1, 2, 3], ' - ');
// Returns: "1 - 2 - 3"
convertArrayToString(['JS', 'TS', 'React'], '|');
// Returns: "JS|TS|React"
convertArrayToString([], ';');
// Returns: ""
API Reference
Parameters
Name | Type | Description |
---|---|---|
array | T[] | Array to convert to a string |
separator | string | Optional. Separator for elements (default: "," ) |
Returns
A string of array elements joined by the specified separator.
Key Features
- Custom Separator: Use any string as a separator (comma, dash, pipe, etc.).
- Type Support: Works with any array element type (stringified as needed).
- Simple API: One line for most use cases.
- Handles Empty Array: Returns an empty string for empty input arrays.
Limitations
- Invalid Input: Throws an error if the input is not a valid array.
- No Deep Serialization: Elements are joined using their string representation. Objects will become
"[object Object]"
unless you stringify them manually. - 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.
Recommended Use Cases
- 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!