135

I'm trying to iterate over a "value" list and convert it into a string. Here is the code:

var blkstr = $.each(value, function(idx2,val2) {                    
     var str = idx2 + ":" + val2;
     alert(str);
     return str;
}).get().join(", ");    

alert() function works just fine and displays the proper value. But somehow, jquery's .get() function doesn't get the right sort of object and fails. What am I doing wrong?

KyleMit
  • 45,382
  • 53
  • 367
  • 544
Neo
  • 10,789
  • 17
  • 50
  • 78
  • 5
    what is "value"? Is it an array? If so var str = value.join(', ') might work just fine. – StefanS Mar 13 '11 at 12:49
  • Yes. If I comment out the .get() part, then I get alert boxes which display "id1:val1", "id2:val2" etc . – Neo Mar 13 '11 at 12:51
  • Do you mean "...get the right *sort* of object"? (A quick proofread before clicking Ask Question is usually a good idea.) (I removed my earlier comment which was rather more strongly put -- this question has a *lot* fewer typos and such than many.) – T.J. Crowder Mar 13 '11 at 12:55

16 Answers16

142

If value is associative array, such code will work fine:

var value = { "aaa": "111", "bbb": "222", "ccc": "333" };
var blkstr = [];
$.each(value, function(idx2,val2) {                    
  var str = idx2 + ":" + val2;
  blkstr.push(str);
});
console.log(blkstr.join(", "));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

(output will appear in the dev console)

As Felix mentioned, each() is just iterating the array, nothing more.

Shadow The Vaccinated Wizard
  • 62,584
  • 26
  • 129
  • 194
134

Converting From Array to String is So Easy !

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

That's it Now A is a string. :)

Spiderman
  • 1,701
  • 1
  • 12
  • 11
  • 12
    I would suggest A.toString() instead so it is more clear what you are doing. – Justin Feb 19 '14 at 20:41
  • 12
    If you do `[1,2,[3]].toString()`, you'll get `1,2,3`, which is pretty rubbish. This answer is just a worse way to write the same call to the same broken, native string method. 42 upvotes?? – Carl Smith Jun 13 '14 at 22:53
  • 10
    you can also join an array like so `['Sunday','Monday','Tuesday','Wednesday','Thursday'].join('');` – etoxin Dec 14 '14 at 23:30
  • 1
    `Array.join()` is definitely the best option, since it won't simply concatenate values with commas, but allow the user to determine how the concatenation should be done. You could use comma+blankspace for example. – Felipe Leão May 24 '16 at 19:01
  • 1
    This is perfect for me. I'm passing in an array which gets changed to a string separated by commas no spaces for an api call. Thanks again. – Nick D Aug 13 '17 at 07:35
121

You can use .toString() to join an array with a comma.

var array = ['a', 'b', 'c'];
array.toString(); // result: a,b,c

Or, set the separator with array.join('; '); // result: a; b; c.

Justin
  • 22,998
  • 16
  • 104
  • 122
  • 3
    I was just hoping for the array to be literally translated into a string and for me to then be forced to use Regex to trim off the fat, but this is Oh So Much Better! Thanks Justin. – cranberry Jan 22 '14 at 02:53
71

not sure if this is what you wanted but

var arr = ["A", "B", "C"];
var arrString = arr.join(", ");

This results in the following output:

A, B, C

Nicholas
  • 4,781
  • 2
  • 18
  • 21
44

Four methods to convert an array to a string.

Coercing to a string

var arr = ['a', 'b', 'c'] + [];  // "a,b,c"

var arr = ['a', 'b', 'c'] + '';  // "a,b,c"

Calling .toString()

var arr = ['a', 'b', 'c'].toString();  // "a,b,c"

Explicitly joining using .join()

var arr = ['a', 'b', 'c'].join();  // "a,b,c" (Defaults to ',' seperator)

var arr = ['a', 'b', 'c'].join(',');  // "a,b,c"

You can use other separators, for example, ', '

var arr = ['a', 'b', 'c'].join(', ');  // "a, b, c"

Using JSON.stringify()

This is cleaner, as it quotes strings inside of the array and handles nested arrays properly.

var arr = JSON.stringify(['a', 'b', 'c']);  // '["a","b","c"]'
CDspace
  • 2,551
  • 17
  • 31
  • 35
VIJAY P
  • 1,133
  • 1
  • 11
  • 14
  • 1
    JSON.stringify also makes a single value look like a proper array and not a string: `[8]` vs `8`. That would be the top answer if I had all the votes. Thanks for mentioning it. – Noumenon Nov 12 '20 at 22:49
17

jQuery.each is just looping over the array, it doesn't do anything with the return value. You are looking for jQuery.map (I also think that get() is unnecessary as you are not dealing with jQuery objects):

var blkstr = $.map(value, function(val,index) {                    
     var str = index + ":" + val;
     return str;
}).join(", ");  

DEMO


But why use jQuery at all in this case? map only introduces an unnecessary function call per element.

var values = [];

for(var i = 0, l = value.length; i < l; i++) {
    values.push(i + ':' + value[i]);
}

// or if you actually have an object:

for(var id in value) {
    if(value.hasOwnProperty(id)) {
        values.push(id + ':' + value[id]);
    }
}

var blkstr = values.join(', ');

∆: It only uses the return value whether it should continue to loop over the elements or not. Returning a "falsy" value will stop the loop.

Felix Kling
  • 705,106
  • 160
  • 1,004
  • 1,072
  • I kind of pasted "cleaned" up code here. I am infact dealing with jquery objects. Thanks, map works perfectly. – Neo Mar 13 '11 at 13:00
  • @Neo: You only need `map` if `value` is a jQuery object. And then you should use `value.map(...).get()`. But if you just have an array of jQuery objects, then you need no `get`. You're welcome :) – Felix Kling Mar 13 '11 at 13:07
13

Use join() and the separator.

Working example

var arr = ['a', 'b', 'c', 1, 2, '3'];

// using toString method
var rslt = arr.toString(); 
console.log(rslt);

// using join method. With a separator '-'
rslt = arr.join('-');
console.log(rslt);

// using join method. without a separator 
rslt = arr.join('');
console.log(rslt);
Deepu Reghunath
  • 4,992
  • 1
  • 22
  • 37
4

this's my function, convert object or array to json

function obj2json(_data){
    str = '{ ';
    first = true;
    $.each(_data, function(i, v) { 
        if(first != true)
            str += ",";
        else first = false;
        if ($.type(v)== 'object' )
            str += "'" + i + "':" + obj2arr(v) ;
        else if ($.type(v)== 'array')
            str += "'" + i + "':" + obj2arr(v) ;
        else{
            str +=  "'" + i + "':'" + v + "'";
        }
    });
    return str+= '}';
}

i just edit to v0.2 ^.^

 function obj2json(_data){
    str = (($.type(_data)== 'array')?'[ ': '{ ');
    first = true;
    $.each(_data, function(i, v) { 
        if(first != true)
            str += ",";
        else first = false;
        if ($.type(v)== 'object' )
            str += '"' + i + '":' + obj2json(v) ;
        else if ($.type(v)== 'array')
            str += '"' + i + '":' + obj2json(v) ;
        else{
            if($.type(_data)== 'array')
                str += '"' + v + '"';
            else
                str +=  '"' + i + '":"' + v + '"';
        }
    });
    return str+= (($.type(_data)== 'array')? ' ] ':' } ');;
}
Ruchit Rami
  • 2,245
  • 3
  • 24
  • 52
buitanan
  • 41
  • 2
3

I needed an array to became a String rappresentation of an array I mean I needed that

var a = ['a','b','c'];
//became a "real" array string-like to pass on query params so was easy to do:
JSON.stringify(a); //-->"['a','b','c']"

maybe someone need it :)

Magico
  • 2,806
  • 1
  • 13
  • 17
3
var arr = new Array();

var blkstr = $.each([1, 2, 3], function(idx2,val2) {                    
    arr.push(idx2 + ":" + val2);
    return arr;
}).join(', ');

console.log(blkstr);

OR

var arr = new Array();

$.each([1, 2, 3], function(idx2,val2) {                    
    arr.push(idx2 + ":" + val2);

});

console.log(arr.join(', '));
Santosh Linkha
  • 13,692
  • 17
  • 72
  • 113
2

convert an array to a GET param string that can be appended to a url could be done as follows

function encodeGet(array){
    return getParams = $.map(array , function(val,index) {                    
        var str = index + "=" + escape(val);
        return str;
   }).join("&");
}

call this function as

var getStr = encodeGet({
    search:     $('input[name="search"]').val(),
    location:   $('input[name="location"]').val(),
    dod:        $('input[name="dod"]').val(),
    type:       $('input[name="type"]').val()
});
window.location = '/site/search?'+getStr;

which will forward the user to the /site/search? page with the get params outlined in the array given to encodeGet.

Fydo
  • 1,320
  • 16
  • 28
1

You shouldn't confuse arrays with lists.

This is a list: {...}. It has no length or other Array properties.

This is an array: [...]. You can use array functions, methods and so, like someone suggested here: someArray.toString();

someObj.toString(); will not work on any other object types, like lists.

GalaxyCat105
  • 2,105
  • 4
  • 12
  • 26
Pedro Ferreira
  • 449
  • 6
  • 12
0

Array.prototype.toString()

The toString() method returns a string representing the specified array and its elements.

var months = ["Jan", "Feb", "Mar", "Apr"];
months.toString(); // "Jan,Feb,Mar,Apr"

Syntax

arr.toString()

Return value

A string representing the elements of the array.

for more information :

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toString

GalaxyCat105
  • 2,105
  • 4
  • 12
  • 26
KARTHIKEYAN.A
  • 11,752
  • 4
  • 81
  • 93
  • Please use a [blockquote](https://meta.stackoverflow.com/questions/343635/how-to-compose-yellow-background-blockquote) to make it clear that the information is *directly copied* from the link. Otherwise, this could be counted as plagiarism. – GalaxyCat105 Dec 03 '20 at 19:11
  • Okay, will follow. – KARTHIKEYAN.A Dec 04 '20 at 06:01
0

Here's an example using underscore functions.

var exampleArray = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
var finalArray = _.compact(_.pluck(exampleArray,"name")).join(",");

Final output would be "moe,larry,curly"

sabin
  • 615
  • 9
  • 14
0

we can use the function join() to make the string from the array, and as parameter of function join we giv it '' empty character.

var newStr =mArray.join('');
Amirouche Zeggagh
  • 2,532
  • 1
  • 17
  • 17
0
const myArray=["hello",4,"programming"];
console.log(myArray.join(''));//hello4programming

We can use the join function for converting

Force Bolt
  • 273
  • 5