Search code examples
javascriptarraysstringiterationseparator

How to replace array commas with different characters in JS?


Given this array ar and a list of separators:

let ar = ["bestes", "haus", "Tiangua"];
const separators = [" ", ""];

How can I convert it into a string, while using as separator each value from the separators array, instead of the usual commas?

Expected result:

res = ["bestes hausTiangua"]

This is my current implementation, but it would use the same separator only.

let kw = ar.join(',').replace.(/,/g, '/')

Solution

  • You can do it in just one operation with the function Array.prototype.reduce:

    ar.reduce((a, s, i) => a + separators[i-1] + s)