-1

I have a multi-dimensional array like this:

1 2 3

4 5 6

Now I need to convert this array into a string like 1,2,3;4,5,6.

Can any one suggest how to do this, please?

1
  • I've fixed up your question a bit, but I don't understand (a) what you have, (b) how you want to transform it and (c) what you've already tried. Jan 11, 2012 at 10:38

3 Answers 3

7

simply use the join method on the array.

> [[1,2,3],[4,5,6]].join(';')
'1,2,3;4,5,6'

It's lucky that you simply don't have to consider how the apply the join method on the inner lists, because a list is joined by comma by default. when a list is coerced into a string, it by default uses commas to separate the items.

3
  • 1
    Just to further clarify here, join is not recursive. This is actually the same as calling [[1,2,3].toString(), [4,5,6].toString()].join(':'). This happens to work, for the trival example given. Jan 11, 2012 at 10:43
  • but that array does not consistent the rows are dynamic one :(
    – Prabakaran
    Jan 11, 2012 at 10:44
  • @jordancpaul thanks for the heads-up :) Edited the answer to make it more clear.
    – qiao
    Jan 11, 2012 at 10:49
1

As it was already mentioned by qiao, join() is not recursive.
But if you handle the recursion yourself you should acquire the desired result, although in a rather inelegant way.

var array = [[1,2,3],[5,6,7]];
    var result = [];

    array.forEach(
             function(el){
                 result.push(
                      el.join(",")
                 );
             });

    result.join(";");
0

If you need to serialize an array into a string and then deserialize it later to get an array from the string you might want to take a look at JSON:

http://www.openjs.com/scripts/data/json_encode.php

Try this:

array.toString();

See here for reference: http://www.w3schools.com/jsref/jsref_tostring_array.asp

  • See answer by qiao for a much nicer approach to multidimensional arrays like this.
3
  • it was multi dimensional array
    – Prabakaran
    Jan 11, 2012 at 10:44
  • And i need to segregate the rows using semi colon
    – Prabakaran
    Jan 11, 2012 at 10:47
  • The solution by qiao will do that for your array... if you need a handling for a more complex array you should give 1-2 example of how the array can look like and how the result should look like then.
    – bardiir
    Jan 11, 2012 at 10:50

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.