Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl: What is the easiest way to flatten a multidimensional array?

What's the easiest way to flatten a multidimensional array ?

like image 603
sid_com Avatar asked Mar 02 '11 11:03

sid_com


People also ask

What does it mean to flatten an 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.

What is flatten method?

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.

What does flatten do in JS?

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.


2 Answers

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
like image 89
Vijayender Avatar answered Sep 28 '22 08:09

Vijayender


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(@$_) : $_ } @_;
}
like image 40
Eugene Yarmash Avatar answered Sep 28 '22 06:09

Eugene Yarmash