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]]
]