Reverse the values of a 2 dimensional array that could extend n times.
[1, [2, [3, ... [n, null]]]]
Given:
- All arrays always have a length of 2
- Last array in the list will contain an index 1 of null
Example:
[1, [2, [3, null]]]will output[3, [2, [1, null]]][1, [2, [3, [4, null]]]]would output[4, [3, [2, [1, null]]]]
I'm not sure if I'm describing it right but I came across this exercise today and came up with a fairly 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 );
I am by no means a javascript expert, so I was wondering if there was a better way to do it?
null? Also, your example seems to leave that out of the final result.null. Something that I missed, apparently.