Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Split array up into n-groups of m size?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 341
    Comment on it

    A very good method i found in ruby so just thought to share it with everyone, so i am writing this blog to share and help others. This particular blog is for splitting up of array into many groups. Lets see this as an example below:

    1) arr = (1..6).to_a
    
    
    2) arr.each_slice(2).to_a # => [[1, 2], [3, 4], [5, 6]]
    
    3) arr.each_slice(3).to_a # => [[1, 2, 3], [4, 5, 6]]
    
    4) arr.each_slice(4).to_a # => [[1, 2, 3, 4], [5, 6]]
    

    In the first line we took a range from 1-6 and convert into an array and after that we are splitting it into different sizes

    A) In line 2 we specified the size as 2

    2) In line 3 we specified the size as 3

    3) In line 4 we specified the size as 4 so the first group would be from 1-4 and second would be just 5-6 because we dont have more numbers in the array

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: