0

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

4 Answers 4

4
selected.join(',')

see Array.join()

Sign up to request clarification or add additional context in comments.

1 Comment

Where I have to use selected.join(',')?
2

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.

2 Comments

var myVar2 = a.join(", "); is joining my values separated by a , Thank u Zaheer..!
Your answer doesn't show how to combine this with the $.each used by OP.
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.

Comments

1

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 :-)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.