Click here to Skip to main content
15,887,371 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:
JavaScript
let data = ["apple", ["banana", "cherry"], "date"];
let result = data.join(", ");
console.log(result);


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!
Posted
Updated 13-Sep-23 3:59am
v3

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 -
JavaScript
let data = ["apple", ["banana", "cherry"], "date"];
let result = data.map(item => Array.isArray(item) ? item.join(", ") : item).join(", ");
console.log(result);

The output will be -
Output
"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