user3094719
user3094719

Reputation: 297

How do I split an array based on the index of its values?

How do I split an Array with an indefinite entries:

["a","b","c","d","e",...]

Into even and odd arrays like:

["a","c","e",...]

and

["b","d","f",...]

Upvotes: 3

Views: 2517

Answers (4)

Mark Thomas
Mark Thomas

Reputation: 37507

If you're using Rails or can require 'active_support' you can do this:

a.in_groups_of(2).transpose

Upvotes: 1

Abdo
Abdo

Reputation: 14051

EDITED: general solution

partitions_number = 2
['a','b','c','d','e'].group_by.with_index { |obj, i| i % partitions_number }.values
=> [["a", "c", "e"], ["b", "d"]]

['a','b','c','d','e'].group_by.with_index { |obj, i| i % 3 }.values
=> [["a", "d"], ["b", "e"], ["c"]]

Upvotes: 0

Kyle
Kyle

Reputation: 22258

Edited based on comment:

arr = [:foo, :foo, :bar, :baz, :qux, :foo]

evens, odds = arr.partition.with_index{ |_, i| i.even? }

evens # [:foo, :bar, :qux]
odds # [:foo, :baz, :foo]

Upvotes: 10

Noah Clark
Noah Clark

Reputation: 8131

Edit after clarification:

You can do something like this:

odds = []
evens = []
array.each_with_index { |el, index| index % 2 == 0 ? evens << el : odds << el }
[odds, evens]

Upvotes: 1

Related Questions