I have an array like this:
const arr = [
['1 1 1', '', '2 2 2'],
['', '3 3 3', '4 4 4']
]
and my goal is to convert it to this array:
[
[ [1,1,1], [2,2,2] ],
[ [3,3,3], [4,4,4] ]
]
I am trying to do that in functional way using function composition. I am also using Ramda.
I have this code
const filterEmpty = filter(o(not, isEmpty));
const getFinalArr = map(
compose( map(map(parseInt)), map(split(' ')), filterEmpty )
)
console.log(getFinalArr(arr))
Is there way to write it with less map nesting? I tried something like this:
const getFinalArr = map(
compose( parseInt, map, map, split(' '), map, filterEmpty )
)
But of course it did not work.
Or if there is another way to easily deal with arrays nested like this, I would appreciate learning about that.
When things start to get long and confusing I prefer R.pipe on R.compose, and writing the function where each line represents one transformation:
const { map, pipe, reject, isEmpty, split } = R
const fn = map(pipe(
reject(isEmpty), // remove empty items
map(split(' ')), // convert string to sub-arrays
map(map(Number)), // convert sub-arrays to arrays of numbers
))
const arr = [['1 1 1', '', '2 2 2'], ['', '3 3 3', '4 4 4']]
const result = fn(arr)
console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.min.js" integrity="sha512-rZHvUXcc1zWKsxm7rJ8lVQuIr1oOmm7cShlvpV0gWf0RvbcJN6x96al/Rp2L2BI4a4ZkT2/YfVe/8YvB2UHzQw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
I'd also suggest considering recursion for this kind of job
const parse = R.pipe(R.split(' '), R.map(Number));
const normalize = R.pipe(R.reject(R.isEmpty), R.map(parse), R.of);
const fn = ([head, ...tail]) => normalize(head).concat(
tail.length ? fn(tail) : [],
);
// ==
const data = [['1 1 1', '', '2 2 2'], ['', '3 3 3', '4 4 4']]
console.log(
fn(data),
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.js" integrity="sha512-3sdB9mAxNh2MIo6YkY05uY1qjkywAlDfCf5u1cSotv6k9CZUSyHVf4BJSpTYgla+YHLaHG8LUpqV7MHctlYzlw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
You could use a slightly different approach by having a look to a solution in pure Javascritp and convert this to Ramda.
parse
const
{ compose, filter, isEmpty, map, not, o, split } = R,
array = [['1 1 1', '', '2 2 2'], ['', '3 3 3', '4 4 4']],
resultPure = array.map(a => a
.filter(Boolean)
.map(s => s
.split(' ')
.map(Number)
)
),
fn = map(compose(
map(compose(
map(Number),
split(' ')
)),
filter(o(not, isEmpty))
));
console.log(fn(array));
console.log(resultPure);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.min.js" integrity="sha512-rZHvUXcc1zWKsxm7rJ8lVQuIr1oOmm7cShlvpV0gWf0RvbcJN6x96al/Rp2L2BI4a4ZkT2/YfVe/8YvB2UHzQw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>