Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting an array into x arrays

I have an array:

arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

I want to split arr1 into x slices, where each slice is as full and equal as possible.

arr2  = arr1.foo(3)
# => [1, 2, 3, 4][5, 6, 7][8, 9, 10]

each_slice does the opposite of what I want, separating the array into groups of x elements instead.

arr2 = arr1.each_slice(3)
# => [1, 2, 3][4, 5, 6][7, 8, 9][10]

If possible, I want to do this without using rails-specific methods like in_groups.

like image 545
Spuck Avatar asked Jun 06 '26 20:06

Spuck


1 Answers

class Array
  def in_groups(n)
    len, rem = count.divmod(n)
    (0...n).map { | i | (i < rem) ? self[(len+1) * i, len + 1] : self[len * i + rem, len] }
  end
end
like image 142
undur_gongor Avatar answered Jun 09 '26 09:06

undur_gongor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!