flatten a non standard array
by Hugh Chapman
HTML
<p>
Non Flat Array: [1,2,3,[4,5,[9,10,11],6],7,8]<br>
<br>
Result:
</p>
<div id="result"></div>
JavaScript
// No Cigar
//var flattened = [1,2,3,[4,5,6],7,8].reduce(function(a, b) {
// if(Array.isArray(b)) {
// var t = a.concat(b);
// };
//}, []);
// womp, womp - didn't work either
//var mapFlattened = [1,2,3,[4,5,6],7,8].map(function(c,i,a){
// if(Array.isArray(c)) {
// var extractedArray = a.splice(i,1);
// a.splice()
// }
//});
// Let's try recursion
// Note - this is ONLY for integers and arrays of integers
var notFlatArray = [1,2,3,[4,5,[9,10,11],6],7,8];
var flat = [];
function isFlat(element, index, array) {
return typeof element == 'number';
}
function flatten(theArray){
theArray.forEach(function flatten(c,i,a){
if(typeof c == 'number') { // == because typeof result is known type (no need to test it as a string)
flat.push(c);
return;
}
c.forEach(function(c){
flat.push(c);
});
});
}
if(!notFlatArray.every(isFlat)) {
flatten(notFlatArray);
} else {
flat = notFlatArray;
}
// recursion
while(!flat.every(isFlat)) {
var tire = flat;
flat = []; // This was the hang up - kept getting undefined without resetting flat
flatten(tire); // :)
}
console.log(flat);
document.querySelector('#result').textContent = flat;