Array Cast to...Array

Hello.
Have some Array = [“1,2,3,4”, “,1,2,3,4”, “1,2,3,4”]; or Dynamic { arr:“1,2,3,4|1,2,3,4|1,2,3,4” }

Want get this : Array<Array> = [ [1,2,3,4], [1,2,3,4], [1,2,3,4] ];

Its real only from FOR LOOPS or maybe secret cast ?

In Haxe, the Array type has a “type parameter”, which needs to be filled.

For example, this would not compile:

var array:Array = [ 1, 2, 3 ];

…but this will:

var array:Array<Int> = [ 1, 2, 3 ];

Similarly, you need to nest type parameters when you have arrays of arrays

var arrays:Array<Array<Int>> = [ [ 1, 2, 3 ], [ 4, 5, 6 ] ];
var moreArrays:Array<Array<Array<Int>>> = [ arrays ];

Another feature that might help, though, is type inference. In many cases, you do not have to write the full type, you can allow the compiler to pick this up automatically.

var arrays = [ [ 1, 2, 3 ], [ 4, 5, 6 ] ];
var moreArrays = [ arrays ];

…I find this much cleaner to write, and there’s no cost at runtime, and you still get compile-time errors if you had typed it :wink:

Sounds like you’re looking for Lambda.map().

using Lambda;

var inputArray:Array<String> =
    ["1,2,3,4", "1,2,3,4", "1,2,3,4"];
var outputArray:Array<Array<Int>> =
    inputArray.map(function(string) {
        return string.split(",").map(Std.parseInt);
    });
trace(outputArray);

var inputString:String = "1,2,3,4|1,2,3,4|1,2,3,4";
outputArray =
    inputString.split("|").map(function(substring) {
        return substring.split(",").map(Std.parseInt);
    });
trace(outputArray);

Haxe 4.0 will allow you to save a little bit of code:

using Lambda;

var inputArray:Array<String> =
    ["1,2,3,4", "1,2,3,4", "1,2,3,4"];
var outputArray:Array<Array<Int>> =
    inputArray.map(string -> string.split(",").map(Std.parseInt));
trace(outputArray);

var inputString:String = "1,2,3,4|1,2,3,4|1,2,3,4";
outputArray =
    inputString.split("|").map(
        string -> string.split(",").map(Std.parseInt));
trace(outputArray);

But in the end, it might be easier to use a normal for loop.

1 Like

Thx!!! Lambda its all i need

You may also be interested in array comprehensions, which cover slightly different situations.

ooo its also good trick