JavaScript implode
Joins array elements placing glue string between items and return one string
1 2 3 4 56 7 8 9 1011 12 13 14 1516 17 18 19 2021 22 23 24 2526 27 28 29 3031 32 33 34 | function implode (glue, pieces) { // Joins array elements placing glue string between items and return one string // // version: 911.718 // discuss at: http://phpjs.org/functions/implode // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + improved by: Waldo Malqui Silva // + improved by: Itsacon (http://www.itsacon.net/) // + bugfixed by: Brett Zamir (http://brett-zamir.me) // * example 1: implode(' ', ['Kevin', 'van', 'Zonneveld']); // * returns 1: 'Kevin van Zonneveld' // * example 2: implode(' ', {first:'Kevin', last: 'van Zonneveld'}); // * returns 2: 'Kevin van Zonneveld' var i = '', retVal='', tGlue=''; if (arguments.length === 1) { pieces = glue; glue = ''; } if (typeof(pieces) === 'object') { if (pieces instanceof Array) { return pieces.join(glue); } else { for (i in pieces) { retVal += tGlue + pieces[i]; tGlue = glue; } return retVal; } } else { return pieces; } } |
Examples
» Example 1
Running
1 | implode(' ', ['Kevin', 'van', 'Zonneveld']); |
Should return
1 | 'Kevin van Zonneveld' |
» Example 2
Running
1 | implode(' ', {first:'Kevin', last: 'van Zonneveld'}); |
Should return
1 | 'Kevin van Zonneveld' |
Dependencies
No dependencies, you can use this function standalone.
Open syntax issues
php.js uses JsLint to help us keep our code consistent and prevent some common bugs.
Eventually we want all code to pass or at least take into consideration most fixes suggested by JsLint, following this JsLint configuration we’ve decided on.
Authors
Thanks to the following developers, you get to have implode goodness in JavaScript.
@Itsacon: Thanks very much! There may be a few other functions out there like that that only work with true arrays, so it is very good to have your fix. FYI, I declared retVal, tGlue, and i with 'var' so they would not be globals. It is now fixed in git: http://github.com/kvz/phpjs/commit/e00889a7914df1e91640b7222d56eee30c20ec97
This is a follow-up on the discussion at the array_diff() function.
The implode function is currently incompatible with most of the array_xxx() functions. Those functions often return objects instead of Arrays, but the implode() function actively checks for Arrays, and returns objects un-imploded.
I made a slight alteration, parsing all object properties as well.
1 2 3 4 56 7 8 9 1011 12 13 14 1516 17 18 19 2021 22 23 24 2526 27 | function implode(glue,pieces) { if(arguments.length == 1) { pieces = glue; glue = ''; } if(typeof(pieces)=='object') { if(pieces instanceof Array) return pieces.join(glue); else { retVal='', tGlue=''; for(i in pieces) { retVal += tGlue + pieces[i]; tGlue = glue; } return retVal; } } else { return pieces; } } |
I also made the function compatible with the PHP 4.3.0 alteration that made the glue parameter optional.


Kevin van Zonneveld
25 Oct '09