-1
const arr = [1,2,[3,4,5,[6,7,[8,9],10]]];

Lets say we have a nested array like above. Is there a specific deep recursion method?

Instead of calling the same function in function or iteratively looping; is there any deepMap function which iterates over all nested items?

Something traverses the object tree entirely.

R.deepMap(function(e){
   console.log(e)
});
//1,2,3,4,5,6,7,8,9,10
serkan
  • 6,885
  • 4
  • 41
  • 49

4 Answers4

2

It's often easier to break it down into smaller bits of functionality, in this case flattening a deeply nested array, and then mapping over it.

const deepMap = f => R.pipe(flatten, map(f))

deepMap(R.inc)(arr)
// -> [2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
Ross Mackay
  • 940
  • 4
  • 10
  • It's unclear from the question whether this is important or not, but this solution does not retain the initial nesting nesting structure. If it's unimportant, than this is a much better solution than my suggestion. But it's not that difficult to retain the structure. – Scott Sauyet Oct 03 '17 at 01:32
  • True, I assumed because the output was comma delimited they meant a flat array, although I agree it's ambiguous – Ross Mackay Oct 03 '17 at 22:55
1

There isn't such a thing built into Ramda. (I don't know quite how we'd type the input.) But it's easy enough to write your own:

const arr = [1,2,[3,4,5,[6,7,[8,9],10]]]

const deepMap = (fn, xs) => map(x => is(Array, x) ? deepMap(fn, x) : fn(x), xs)

deepMap(n => n * n, arr) //=> [1, 4, [9, 16, 25, [36, 49, [64, 81], 100]]]

You can see this in action on the Ramda REPL

Scott Sauyet
  • 49,207
  • 4
  • 49
  • 103
0

you could do

const arr = [1,2,[3,4,5,[6,7,[8,9],10]]];

function flatten(arr){
    return arr.reduce((a, b) => {
        if(b instanceof Array)
            a = a.concat(flatten(b));
        else
            a.push(b);
        return a;
    }, []);
}

console.log(flatten(arr));
marvel308
  • 10,288
  • 1
  • 21
  • 32
0

You could use R.flatten method to flat your nested array in one array.

Then use R.forEach method to apply a function on all the new array items.

Ex:

const arr = [1,2,[3,4,5,[6,7,[8,9],10]]];

R.forEach(function (e) {
  console.log(e);
}, R.flatten(arr))
<script src="//cdn.jsdelivr.net/ramda/latest/ramda.min.js"></script>
Mohamed Abbas
  • 2,228
  • 1
  • 11
  • 19