2

I'm looking for a good way to reverse multi-dimensional array in javascript but at a specific level (n) only, like:

[
        [[2,1], [4,2], [6,3], [3,4]], 
        [[5,1], [1,2], [3,3], [4,4]], 
        [[4,1], [7,2], [1,3], [2,4], ['monkey', [3,4,5,6,7]]]
]

into this (with n = 2):

[
        [[1,2], [2,4], [3,6], [4,3]], 
        [[1,5], [2,1], [3,3], [4,4]], 
        [[1,4], [2,7], [3,1], [4,2], [[3,4,5,6,7], 'monkey']]
]

For the time being, I've coded this short prototype which meets my need:

    Array.prototype.reverseAtLevel = function(level){
        if(level < 0)
            return;
        if(level == 0)
            this.reverse();
        this.forEach(function(element, index, array){
            if(element instanceof Array)
                element.reverseAtLevel(level-1);
        });
        return;
    };

Using it like this:

aMultiDim.reverseAtLevel(2)

Is this the right approach to take?

EDIT: I don't want to have the "direct" .reverse() behaviour which will output my first example as:

[
        [[4,1], [7,2], [1,3], [2,4], ['monkey', [3,4,5,6,7]]],
        [[5,1], [1,2], [3,3], [4,4]], 
        [[2,1], [4,2], [6,3], [3,4]]
]
AnomalySmith
  • 597
  • 2
  • 5
  • 16
  • 3
    so it works? If you after feedback you'd be better off putting this on http://codereview.stackexchange.com/ – Liam Aug 07 '15 at 13:10
  • I dont think you are actually doing anything with this. All you are doing is passing the same array to some lower level and then when you reach at level 0(which you will for sure). you are reversing the array. **So how is it different from reversing the array directly. All it does is reverse eventually**. Looks very useless to me. I may be wrong, but this is what I felt by seeing your program. – govindpatel Aug 07 '15 at 13:18
  • I actually get my array reversed only with the couples you can see in my example. I'm not looking for reversing everything or the order of the three first level array on my example (which is the behaviour of "reverse directly"), just at a precise n level. Anyway, I admit my example was not the best I could use. – AnomalySmith Aug 07 '15 at 13:28

0 Answers0