1

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.

1 Answer 1

2

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.

  1. The initial input goes to transpose
  2. The result of transpose(arr) is given to map(join("")) which applies join("") to all sub arrays
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.