Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to group array elements by index?

I have the array arr which I want to group by indexes given in array idx. I mean,

  • sub array 1 will end at index 1
  • sub array 2 will end at index 5
  • sub array 3 will end at index 7
  • sub array N will be formed from element at index 8 to last element of arr

With my current code I can group the first sub array with first index of idx idx[0] = 1.

Then, How to replicate for all indexes within array idx? Thanks in advance.

My current code and output is this:

idx = [1,5,7]
arr = ['a','b','c','d','e','f','g','h','i','j','k']

arr.group_by.with_index { |z, i| i <= idx[0] }.values
=> [["a", "b"], ["c", "d", "e", "f", "g", "h", "i", "j", "k"]]

and my desired output is like this:

output   --> [["a", "b"], ["c", "d", "e", "f"], ["g", "h"], ["i", "j", "k"]]

#Indexes -->    0    1      2    3    4    5      6    7      8    9    10  
like image 536
Ger Cas Avatar asked Jan 26 '23 03:01

Ger Cas


2 Answers

You can use slice_after to slice the array after each item whose index is in idx:

idx = [1, 5, 7]
arr = %w[a b c d e f g h i j k]

arr.enum_for(:slice_after).with_index { |_, i| idx.include?(i) }.to_a
#=> [["a", "b"], ["c", "d", "e", "f"], ["g", "h"], ["i", "j", "k"]]

That enum_for is (unfortunately) needed to chain slice_after and with_index.

like image 198
Stefan Avatar answered Jan 29 '23 08:01

Stefan


Another solution

idx = [1, 5, 7]
arr = ['a','b','c','d','e','f','g','h','i','j','k']
from = 0

arr.map.with_index { |a, i|  
  if idx.include?(i)
    result = arr[from..i]  
    from = i + 1 
  end
  result
}.compact

 => [["a", "b"], ["c", "d", "e", "f"], ["g", "h"]] 
like image 33
Dyaniyal Wilson Avatar answered Jan 29 '23 06:01

Dyaniyal Wilson