Skip to content
Advertisement

Join specific items in an array [closed]

I would like to join the items in a string array that contain values and keep the empty items.

JavaScript

For the above example, I would like to achieve the following outcome:

JavaScript

I tried using reduce, but couldn’t figure out the solution.

JavaScript

Advertisement

Answer

You can use reduce and check whether the last produced entry or the current string is empty. If so, the current string should be a separate entry, otherwise it should be concatenated to the previous entry:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement