Skip to content

Instantly share code, notes, and snippets.

@retgoat
Last active July 3, 2017 11:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save retgoat/040cd93b21e8ec15f02faa157019f264 to your computer and use it in GitHub Desktop.
Save retgoat/040cd93b21e8ec15f02faa157019f264 to your computer and use it in GitHub Desktop.

Flat an array without using Array#flatten method

Ruby

ary = [[1, 2, [3], []], 4]

Recursion

ary.flat_map{|element| element.kind_of?(Array) ? element.flat_map{|i| i} : element }
=> [1, 2, 3, 4]

Another recursion

def flats(ary)
  ary.each_with_object([]) do |element, acc|
    acc.push *(element.kind_of?(Array) ? flats(element) : element)
  end
end

2.2.5 :136 >   flats ary
 => [1, 2, 3, 4]

Longer version

ary.inject([]){|acc, value| element = value.kind_of?(Array) ? value.flat_map{|i| i} : value; acc << element}.flat_map{|j|j}
=> [1, 2, 3, 4]

Elixir

defmodule Lst do
  def flattn(ary) do
    case ary do
      [] -> []
      [h|t] -> flattn(h) ++ flattn(t)
      h -> [h] 
    end
  end

  def fltn(list, acc \\ [])
  def fltn([], acc), do: Enum.reverse(acc)
  def fltn([h|t], acc) when is_list(h), do: fltn(h ++ t, acc)
  def fltn([h|t], acc), do: fltn(t, [h|acc])
end
iex(71)> Lst.fltn ary
[1, 2, 3, 4]

iex(72)> Lst.flattn ary
[1, 2, 3, 4]
iex(73)>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment