javaScript Array.join("")
javascript array join() method - Stack Overflow
javascript - Perform .join on value in array of objects - Stack Overflow
How can I merge this array into one large ArrayBuffer?
new Array(width - this.length + 1).join(char)
This ^ is effectively saying "make an empty array with n number of slots, then join the empty slots together using the char to separate each empty slot. So, if char = "0", and n = 3, we get 000.
width - this.length + 1 is used to determine the number of characters needed to be added to beginning of the string.
Then we add that to the beginning of the original string: this
+1
You need the + 1 because of how join works.
new Array(1).join('0') = "" // wrong
new Array(1+1).join('0') = "0" // correct
new Array(2).join('0') = "0" // wrong
new Array(2+1).join('0') = "00" // correct
When you join an array with N elements, there will be N-1 separators between the elements. The code is using join to create a string with just N separators, so you need to give it an array with N+1 elements to account for this.
If you want to map objects to something (in this case a property). I think Array.prototype.map is what you're looking for if you want to code functionally.
(fiddle)
If you want to support older browsers, that are not ES5 compliant you can shim it (there is a polyfill on the MDN page above). Another alternative would be to use underscorejs's pluck method:
var users = [
{name: "Joe", age: 22},
{name: "Kevin", age: 24},
{name: "Peter", age: 21}
];
var result = _.pluck(users,'name').join(",")
Well you can always override the toString method of your objects:
var arr = [
{name: "Joe", age: 22, toString: function(){return this.name;}},
{name: "Kevin", age: 24, toString: function(){return this.name;}},
{name: "Peter", age: 21, toString: function(){return this.name;}}
];
var result = arr.join(", ");
console.log(result);
Run code snippetEdit code snippet Hide Results Copy to answer Expand