Home:ALL Converter>Iterate over an array in javascript and concat it to another variable

Iterate over an array in javascript and concat it to another variable

Ask Time:2013-09-24T13:22:23         Author:Sanjay Malhotra

Json Formatter

I have an array in javascript. I have to iterate over it and concat the values to a variable and each value should be separated by comma.

This is my code:

var selected = new Array();
jQuery("input[type=checkbox]:checked").each(function() {
    selected.push(jQuery(this).attr('id'));
});

Author:Sanjay Malhotra,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/18973514/iterate-over-an-array-in-javascript-and-concat-it-to-another-variable
user180100 :

selected.join(',')\n\n\nsee Array.join()",
2013-09-24T05:25:12
Zaheer Ahmed :

You need Array.join()\n\nvar a = new Array(\"Wind\",\"Rain\",\"Fire\");\nvar myVar1 = a.join(); // assigns \"Wind,Rain,Fire\" to myVar1\nvar myVar2 = a.join(\", \"); // assigns \"Wind, Rain, Fire\" to myVar2\nvar myVar3 = a.join(\" + \"); // assigns \"Wind + Rain + Fire\" to myVar3\n\n\nIssues:\n\nIt wont work with arguments because the arguments object is not an array, although it looks like it. It has no join method:\n\nfunction myFun(arr) {\n return 'the list: ' + arr.join(\",\");\n} \nmyFun(arrayObject);\n\n\nwill throw\n\nTypeError: arr.join is not a function\n\nbecause arr is not a jQuery object, just a regular JavaScript object.",
2013-09-24T05:35:43
Kiran Kumar Veerabatheni :

Use the below code.\n\nvar namesArray = new Array(\"John\", \"Micheal\", \"Doe\",\"Steve\",\"Bob\"); //array\nvar resultString = \"\"; // result variable\n\n//iterate each item of array\nfor (var i = 0; i < namesArray.length; i++) \n resultString += namesArray[i] + \",\";\n\n//remove the extra comma at the end, using a regex\nresultString = resultString.replace(/,(?=[^,]*$)/, '')\n\nalert(resultString); \n\n\nGood Luck.",
2013-09-24T05:40:55
yy