Home > Back-end >  How to iterate an array every 30 items
How to iterate an array every 30 items

Time:09-28

I have an array of products with 234 items. I need to create another array with a pagination (every 10 items) example:

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

How can I solve this? I've tried in_groups_of but I don't have success.

CodePudding user response:

You're looking for each_slice

Whenever you have an array problem, check the Enumerable. in_groups_of is a Rails method and uses each_slice under the hood.

CodePudding user response:

Just use Enumerable#each_slice

[*1..34].each_slice(10).to_a

# =>
# [
#   [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
#   [11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
#   [21, 22, 23, 24, 25, 26, 27, 28, 29, 30],
#   [31, 32, 33, 34]
# ]
  •  Tags:  
  • ruby
  • Related