Search code examples
javascriptarraysline-breaks

How to break lines in javascript using .join


I have 9 strings "a", "b", "c", "d", "e", "f", "g", "h", "i" in a JavaScript array.

const arr = ["a", "b", "c", "d", "e", "f", "g", "h", "i"];

I am printing the value of arr using JavaScript alert box.

but, if I use arr.join(" ") it is expected like:

a b c d e f g h i

but, I want to change the line for every 3rd element. like:

a b c
d e f
g h i

How can I do this?


Solution

  • You can use a for loop with Array#slice.

    const arr = ["a", "b", "c", "d", "e", "f", "g", "h", "i"];
    const parts = [];
    for(let i = 0; i < arr.length; i += 3){
      parts.push(arr.slice(i, i + 3).join(' '));
    }
    console.log(parts.join('\n'));