What's the easiest way to flatten a multidimensional array ?
To flatten an array means to reduce the dimensionality of an array. In simpler terms, it means reducing a multidimensional array to a specific dimension. There are certain situations in which the elements of an array are an array, generally referred to as nested arrays.
Prototype - flatten() Method This method returns a flat (one-dimensional) version of the array. Nested arrays are recursively injected inline. This can prove very useful when handling the results of a recursive collection algorithm.
flatten() function is an inbuilt function in Underscore. js library of JavaScript which is used to flatten an array which is nested to some level. The resultant array will have no depth. It will be completely flattened. If pass the shallow parameter then the flattening will be done only till one level.
One level of flattening using map
$ref = [[1,2,3,4],[5,6,7,8]]; # AoA
@a = map {@$_} @$ref; # flattens it
print "@a"; # 1 2 3 4 5 6 7 8
Using List::Flatten
seems like the easiest:
use List::Flatten;
my @foo = (1, 2, [3, 4, 5], 6, [7, 8], 9);
my @bar = flat @foo; # @bar contains 9 elements, same as (1 .. 9)
Actually, that module exports a single simple function flat
, so you might as well copy the source code:
sub flat(@) {
return map { ref eq 'ARRAY' ? @$_ : $_ } @_;
}
You could also make it recursive to support more than one level of flattening:
sub flat { # no prototype for this one to avoid warnings
return map { ref eq 'ARRAY' ? flat(@$_) : $_ } @_;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With