Javascript Exercise - Reverse 2-Dimensional Array

Discard the values โ€‹โ€‹of a 2-dimensional array that can stretch n times.

 [1, [2, [3, ... [n, null]]]] 

Considering:

  • All arrays always have a length of 2
  • The last array in the list will contain index 1 of zero

Example:

  • [1, [2, [3, null]]] outputs [3, [2, [1, null]]]
  • [1, [2, [3, [4, null]]]] outputs [4, [3, [2, [1, null]]]]

I'm not sure that I am describing this correctly, but today I came across this exercise and came up with a pretty obvious solution.

 var ars = [1, [2, [3, null]]], rev = null; function r(x) { rev = (rev == null) ? [x[0]] : [x[0], rev]; if( x[1] !== null ) r(x[1]); } r(ars); console.log( rev ); 

http://jsfiddle.net/5b4xntwg/

I'm not at all a javascript expert, so I was wondering if there is a better way to do this?

+7
javascript arrays
source share
1 answer

Here's a more concise approach that has no side effects:

 function r(arr, acc) { acc = acc || null; return arr ? r(arr[1], [arr[0], acc]) : acc; } 

http://jsfiddle.net/5b4xntwg/1/

It makes the following recursive calls to enter [1, [2, [3, null]]] :

 r([1, [2, [3, null]]] ) r([2, [3, null]] , [1, null] ) r([3, null] , [2, [1, null]] ) r(null , [3, [2, [1, null]]]) 

The last call to arr has null (this is the base case), so it just returns acc , which has the value [3, [2, [1, null]]] .

It should be mentioned that this structure of nested arrays is basically a list of minuses , which is widely used in functional programming and is very conducive to recursive operations.

Finally, here is the iterative version:

 function r(arr) { var acc = null; while (arr) { acc = [arr[0], acc]; arr = arr[1]; } return acc; } 
+8
source share

All Articles