Sanjay Malhotra
Sanjay Malhotra

Reputation: 161

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

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'));
});

Upvotes: 0

Views: 10198

Answers (4)

JD Osterman
JD Osterman

Reputation: 11

OR, rather than have to remove the extra comma, add the final element outside of the for loop :

for (var i = 0; i < namesArray.length-1; i++)
    resultString += namesArray[i] + ", ";
resultString += namesArray[namesArray.length-1];

Yes, I know this is an old post :-)

Upvotes: 1

Zaheer Ahmed
Zaheer Ahmed

Reputation: 28578

You need Array.join()

var a = new Array("Wind","Rain","Fire");
var myVar1 = a.join();      // assigns "Wind,Rain,Fire" to myVar1
var myVar2 = a.join(", ");  // assigns "Wind, Rain, Fire" to myVar2
var myVar3 = a.join(" + "); // assigns "Wind + Rain + Fire" to myVar3

Issues:

It wont work with arguments because the arguments object is not an array, although it looks like it. It has no join method:

function myFun(arr) {
   return 'the list: ' + arr.join(",");
} 
myFun(arrayObject);

will throw

TypeError: arr.join is not a function

because arr is not a jQuery object, just a regular JavaScript object.

Upvotes: 2

Use the below code.

var namesArray = new Array("John", "Micheal", "Doe","Steve","Bob"); //array
var resultString = ""; // result variable

//iterate each item of array
for (var i = 0; i < namesArray.length; i++) 
     resultString += namesArray[i] + ",";

//remove the extra comma at the end, using a regex
resultString = resultString.replace(/,(?=[^,]*$)/, '')

alert(resultString); 

Good Luck.

Upvotes: 2

user180100
user180100

Reputation:

selected.join(',')

see Array.join()

Upvotes: 4

Related Questions