Reputation: 123
Given a 2d matrix of strings, I would like to concatenate the elements in the sublists based on their position.
e.g. Given this data structure as input:
[['x','y' ,'z'],['A', 'B', 'C'], ['a', 'b', 'c']]
The algorithm would produce the output:
['xAa', 'yBb', 'zCc']
I tried R.transpose
, but it gets me [['x','A','a'], ['y', 'B', 'b'], ['z', 'C', 'c']]
, however I couldn't find a way to concatenate the nested strings.
I also tried R.zipWith
, but it doesn't look ideal since R.zipWith
takes only two arguments so that I need to apply it twice to get the output.
Upvotes: 1
Views: 580
Reputation: 18901
You weren't that far off I think.
With transpose
you managed to get this:
[['x','A','a'], ['y', 'B', 'b'], ['z', 'C', 'c']]
Then you just need to map over this array of arrays and join each of them.
e.g.
const {compose, map, join, transpose } = R
const concat_arr = compose(map(join("")), transpose);
const result = concat_arr([['x','y' ,'z'],['A', 'B', 'C'], ['a', 'b', 'c']]);
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.min.js"></script>
Where compose
, map
, join
and transpose
are all Ramda functions.
transpose
transpose(arr)
is given to map(join(""))
which applies join("")
to all sub arraysUpvotes: 2