I think at some point I needed this function for something, don’t remember what for. Anyway, what this does is it makes a multidimensional array a one dimensional.
KK_fnc_arrayFlatten = {
private ["_res", "_fnc"];
_res = [];
_fnc = {
{
if (typeName _x isEqualTo "ARRAY") then [
{_x call _fnc; false},
{_res pushBack _x; false}
];
} count _this;
};
_this call _fnc;
_res
};
So the result is ordered exactly as elements appear in the array:
_arr = [1,2,3,[4,5,6,[7,8,9]],10,11,[12,13,14]];
_res = _arr call KK_fnc_arrayFlatten;
hint str _res; // [1,2,3,4,5,6,7,8,9,10,11,12,13,14]
However if you don’t much care about the order, then there is a faster way to flatten array:
KK_fnc_arrayFlattenUnordered = {
_this = +_this;
for [{private _i = 0}, {_i < count _this}, {_i = _i + 1}] do {
if (_this select _i isEqualType []) then {
_this append (_this deleteAt _i);
_i = _i - 1;
};
};
_this
};
It is about 2 times faster. It also returns a copy, but if the copying is removed and array is modified by reference it could be even faster:
_arr = [1,2,3,[4,5,6,[7,8,9]],10,11,[12,13,14]];
_res = _arr call KK_fnc_arrayFlattenUnordered;
hint str _res; // [1,2,3,10,11,4,5,6,12,13,14,7,8,9]
Enjoy,
KK
EDIT: Updated KK_fnc_arrayFlattenUnordered