Home > Mobile >  Javascript join array with brackets
Javascript join array with brackets

Time:03-11

In javascript I need to join an array into a string with brackets. For example ['abc', 'yte', 'juu'] => (abc)(yte)(juu). I need the fastest and cleanest way to do this. I tried using the array join operator but it doesnt work on the first and last element.

CodePudding user response:

You can do it with template literals. Use join() with )( separator, and wrap the result with ():

const data = ['abc', 'yte', 'juu'];

const result = `(${data.join(')(')})`;
console.log(result);

CodePudding user response:

Thinking "I need the fastest and cleanest way to do this." is often not ideal. In most cases what people want is the most readable and understandable way to implement a solution.

I quite like the following. Where we first bracket each item in the array with map and then join the items with no delimiter:

const data = ['abc', 'yte', 'juu'];
let brackets = data.map(x => "("   x   ")");
let result = brackets.join("")
console.log(result);

That of course takes two passes over the array. If you really must have the fastest solution just use a for loop:

const data = ['abc', 'yte', 'juu'];
let result = "";
for (let item of data) {
    result  = "("   item   ")";
}
console.log(result);

CodePudding user response:

const list = ['abc', 'yte', 'juu'];
const result = list.map(value => `(${value})`).join("");
console.log(result);

CodePudding user response:

In order to reduce an array to a single value (be that an object, array, string, number, ...) Javascript has the Array.prototype.reduce method, which achieves the desired result in a single loop and line:

console.log(['abc', 'yte', 'juu'].reduce((a,v)=>`${a}(${v})`,''))

  • Related