Benjamin Crouzier Benjamin Crouzier - 1 year ago 69
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:


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(string );‚Äč


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

["false", "true", "true", "false", "false", "false", "false"]
[object Object]

Fiddle here:

How do I convert the selectedElements to array ?

Answer Source

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') + "";

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

selectedElements = selectedElements.join()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download