Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to flatten an array of arrays - but not all the way down

What's the best way to convert this

[[["Club three Team one", 7800], ["Club three Team two", 7801]], [], [["Club four Team one", 7807], ["Club four Team two", 7808]], []] 

into

[["Club three Team one", 7800], ["Club three Team two", 7801], ["Club four Team one", 7807], ["Club four Team two", 7808]] 

in ruby? flatten converts this all the way down to

["Club three Team one", 7303, "Club three Team two", 7304, "Club four Team one", 7310, "Club four Team two", 7311] 
like image 886
Addy Avatar asked Apr 10 '11 15:04

Addy


People also ask

How does flattening an array work?

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. let arr = [[1, 2],[3, 4],[5, 6, 7, 8, 9],[10, 11, 12]]; and we need to return a new flat array with all the elements of the nested arrays in their original order.


1 Answers

use flatten(1) http://apidock.com/ruby/Array/flatten

your_array = [[["Club three Team one", 7800], ["Club three Team two", 7801]], [], [["Club four Team one", 7807], ["Club four Team two", 7808]], []] your_array.flatten(1) #=> [["Club three Team one", 7800], ["Club three Team two", 7801], ["Club four Team one", 7807], ["Club four Team two", 7808]] 
like image 98
fl00r Avatar answered Sep 28 '22 00:09

fl00r