Fix the Error: Flattening an Array

Published by Helen Yu in

I'm trying to write a function to flatten an array of subarrays into one array. In other words, I want to transform this: [[1, 2], [3, 4]] into [1, 2, 3, 4].

Here is my code:

def flatten(arr)
  res = []
  for i in 0..arr.size-1
    res + arr[i]
  end
  res
end

But...it doesn't seem to be working! Fix my code so that it correctly flattens the array.

Examples

flatten([[1, 2], [3, 4]]) ➞ []
// Expected: [1, 2, 3, 4]

flatten([["a", "b"], ["c", "d"]]) ➞ []
// Expected: ["a", "b", "c", "d"]

flatten([[true, false], [false, false]]) ➞ []
// Expected: [true, false, false, false]

Notes

N/A

Watch a quick demo on how Edabit works.