Given an array:
arr = [['a', '1'], ['b','2'], ['c', '3']]
Whats the best way to split it into two arrays?
For example from the array above I want to get the following two arrays:
first = ['a','b','c']
second = ['1', '2', '3']
Can i do this using collect
?
To divide an array into two, we need at least three array variables. We shall take an array with continuous numbers and then shall store the values of it into two different variables based on even and odd values.
The split() method splits (divides) a string into two or more substrings depending on a splitter (or divider). The splitter can be a single character, another string, or a regular expression. After splitting the string into multiple substrings, the split() method puts them in an array and returns it.
Using the copyOfRange() method you can copy an array within a range. This method accepts three parameters, an array that you want to copy, start and end indexes of the range. You split an array using this method by copying the array ranging from 0 to length/2 to one array and length/2 to length to other.
ok i just stumbled upon arr.transpose
arr = [['a', '1'], ['b','2'], ['c', '3']].transpose
first = arr[0]
second = arr[1]
compared to the answers above arr.zip
, arr.map
, and the foreach
, which is more efficient?
Or which is the most elegant solution?
OR
(Thanks to comment by Jörg W Mittag - see comment below)
first, second = arr.transpose
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