JavaScript: How to Implode (Flatten) an Array into a String Programming 17 FEB 2012

Coming from PHP, I’m well versed in using the handy implode function to flatten an array into a string, specifying the delimiter character to be used to indicate the border between the flattened array elements.

Happily for me, plain old vanilla JavaScript also has this ability built into the language, choosing to call its version of this functionality “join”.

From the official definition: The join() method joins all elements of an array into a string, and returns the string.

The elements will be separated by a specified separator. If this is ommitted, then the default separator of a comma (,) will be used.

A few examples on using join:

var fruits = ["Banana", "Orange", "Apple", "Mango"];

//a few example usages
document.write(fruits.join() + "<br />");
document.write(fruits.join("+") + "<br />");
document.write(fruits.join(" and "));

//the output:
//Banana and Orange and Apple and Mango


Related Posts:

About Craig Lotter

South African software architect and developer at Touchwork. Husband to a cupcake baker and father to two little girls. I don't have time for myself any more.