onit
onit

Reputation: 2372

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, '/')

Upvotes: 1

Views: 193

Answers (2)

Rodrigo Rodrigues
Rodrigo Rodrigues

Reputation: 8556

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

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

Upvotes: 2

CertainPerformance
CertainPerformance

Reputation: 370689

Iterate over the array and shift from the separators every index.

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

let str = ar[0];
for (let i = 1; i < ar.length; i++) {
  str += separators.shift() + ar[i];
}
console.log(str);

Upvotes: 1

Related Questions