Benjamin Crouzier Benjamin Crouzier - 1 month ago 12
jQuery Question

How to cast an array to string after using the jQuery map function?

I am using the .map function to convert elements to an array, and I'd like to then convert this array into a string:

javascript:

var selectedElements = $('.data').map(function() {
return $(this).hasClass('selected') ? 'true' : 'false';
});

var A = ['Sunday','Monday','Tuesday','Wednesday','Thursday']
A = A + "";

var string = selectedElements + "";

console.log("\ndebug:");
console.log(selectedElements);
console.log(A);
console.log(string );‚Äč


html:

<div class='data'></div>
<div class='data selected'></div>
<div class='data selected'></div>
<div class='data'></div>
<div class='data'></div>
<div class='data'></div>
<div class='data'></div>


Console output:

debug: fiddle.jshell.net:29
["false", "true", "true", "false", "false", "false", "false"]
Sunday,Monday,Tuesday,Wednesday,Thursday
[object Object]


Fiddle here: http://jsfiddle.net/F8ufE/

How do I convert the selectedElements to array ?

Answer

According to the .map() docs:

As the return value is a jQuery object, which contains an array, it's very common to call .get() on the result to work with a basic array.

So if you want to get the actual array you can use get method, like this:

var selectedElements = $('.data').map(function() {
    return $(this).hasClass('selected') + "";
}).get();

For converting an array to a string you can use join method:

selectedElements = selectedElements.join()