Recursively flatten an array
I was asked this recently during a phone interview and, in my nervousness, struggled to come up with something elegant.
Afterwards, I quickly banged this out (of course, stupid brain):
# Goal: recursively flatten array
# flatten([[1, [], [2, 3]], [[[[4]]]], 5]) # => [1, 2, 3, 4, 5]
def flatten(array, flattened = Array.new)
array.each_with_index do |elem, i|
if elem.is_a?(Array)
flatten(elem, flattened)
else
flattened << elem
end
end
flattened
end
puts flatten([[1, [], [2, 3]], [[[[4]]]], 5])
# => [1, 2, 3, 4, 5]
Written by Drew Samsen
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Interview
Authors
Related Tags
#interview
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#