I would like to make an N-dimensional array flatten into a single array. The array will only have numbers, but every element need not necessarily be an array itself. Sample data: (md=multi-dimensional) fiddle
var mdArray = [1,2,[3, 4], [[[5, 6, 7]]]];
Array.prototype.flattenAll = function () {
var self = this,
//finds elements that are not arrays
numbers = $.grep(self, function (n, i) {
return !$.isArray(n);
}),
//gets md arrays
nestedArrays = $.grep(self, function (n, i) {
return $.isArray(n);
}),
returnArray = [];
nestedArrays = $.map(nestedArrays, function (a, ix) {
return a.flatten();
});
return returnArray.concat(numbers).concat(nestedArrays);
};
Array.prototype.flatten = function () {
return this.reduce(function (a, b) {
return a.concat(b);
});
}
The flatten function works for a simple array of arrays, but not for arrays with a rank > 1. This seems like an easy fix with recursion, but I'm not seeing it. What am I missing here to get flatten to run until there are no more arrays to flatten?