How to flatten a 2D array into a sorted one-dimensional array in Ruby

1 Answer

0 votes
# Function that flattens a 2D array and returns a sorted 1D array
def flatten_and_sort(array2d)

  # 1. Flatten the 2D array into a single array
  #    Ruby's flatten(1) flattens only one level (perfect for 2D arrays)
  flattened = array2d.flatten(1)

  # 2. Sort the flattened array
  flattened.sort
end

array2d = [
  [4, 5, 3],
  [30, 20],
  [10],
  [1, 2, 6, 7, 8]
]

arr = flatten_and_sort(array2d)

# Print result as comma‑separated values
puts arr.join(", ")



=begin
run:

1, 2, 3, 4, 5, 6, 7, 8, 10, 20, 30

=end

 



answered 2 hours ago by avibootz

Related questions

...