I have the array arr
which I want to group by indexes given in array idx
. I mean,
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
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
.
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"]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With