5

I'm relatively new to programming and I was wondering how I would convert an array:

[[0,0,0,0,0,0],
 [1,1,1,1,1,1],
 [2,2,2,2,2,2],
 [3,3,3,3,3,3],
 [4,4,4,4,4,4],
 [5,5,5,5,5,5]];

into a string of comma and line-return delineated indices, like:

"0,0,0,0,0,0
1,1,1,1,1,1
2,2,2,2,2,2
3,3,3,3,3,3
4,4,4,4,4,4
5,5,5,5,5,5"

with a dynamic function? I've searched for an implode() function but I couldn't find anything. Thanks in advance!

3 Answers 3

9
private function joinArrays(array:Array):String
{
    var result:String = "";
    for each(var a:Array in array)
    {
        result += a.join() + "\n";
    }
    return result;
}

Or if you don't want the line break after the last line:

var result:String = "";
var length:Number = array.length;
for(var i:Number = 0; i < length; i++) 
{
    result += array[i].join();
    if(i != length - 1)
        result += "\n";
}
return result;
Sign up to request clarification or add additional context in comments.

1 Comment

The default joining character when toString() is called is , so you could cut out the for entirely and just go with trace(array.join("\n")); this would also solve your terminating line break problem
4

A simple .toString() will do the job !

var a:Array=[[0,0,0,0,0,0],[1,1,1,1,1,1],[2,2,2,2,2,2],[3,3,3,3,3,3],[4,4,4,4,4,4],[5,5,5,5,5,5]];
trace(">",a.toString());
//> 0,0,0,0,0,0,1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3,4,4,4,4,4,4,5,5,5,5,5,5

EDIT : As often, RegExp will save your soul : )

var a:Array=[[0,0,0,0,0,0],[1,1,1,1,1,1],[2,2,2,2,2,2],[3,3,3,3,3,3],[4,4,4,4,4,4],[5,5,5,5,5,5]];
var columns:int=11;//columns count
trace(a.toString().replace(new RegExp("(.{"+columns+"})(,?)","g"),"$1\n"));
//output :
//0,0,0,0,0,0
//1,1,1,1,1,1
//2,2,2,2,2,2
//3,3,3,3,3,3
//4,4,4,4,4,4
//5,5,5,5,5,5

1 Comment

haven't seen the "line-return delineated indices" sorry !! ; )
1
function join_arr(arr) {
    var newarr = [];
    for (var i = 0; i < arr.length; i++) {
        newarr.push(arr[i].join(","));
    }
    return newarr.join("\n");
}

Haven't tested it but should work :)

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.