Click here to Skip to main content
15,798,592 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm working on a problem involving nested arrays and string conversion. My array contains both strings and arrays, and I want to build a string representation that preserves the nested structure, similar to the example provided by scaler in this post.

This is my code:
let data = ["apple", ["banana", "cherry"], "date"];
let result = data.join(", ");

What I have tried:

My intention was to receive apple, banana, cherry, and date, but instead, I got apple, banana,cherry, and date. The space around "banana" is gone, and it's unclear where the nested arrays start and stop. How can I modify the code to handle nested arrays correctly during conversion?

Any insights would be much appreciated. Thank you very much!
Updated 13-Sep-23 4:59am

1 solution

The missing space is due to the way you are joining the data. It concatenates the array elements with the specified separator, but it doesn't add spaces automatically after the comma. You should use -
let data = ["apple", ["banana", "cherry"], "date"];
let result = => Array.isArray(item) ? item.join(", ") : item).join(", ");

The output will be -
"apple, banana, cherry, date"

a Working fiddle - Correct Joining Method[^]
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900