Flattening Arrays - ONLY JS
A way to flatten arrays, without using a library, and using recursion.
by Vanessa RC
JavaScript
function flattening(arr) {
// I'm a steamroller, baby
var final = [];
function flatten(elem){
// circulate through the array horizontally
for (var i = 0, len = elem.length; i < len; i++){
// if the element length isnt one - then loop through those elements until finished
// then follow with the rest of the array
if (Array.isArray(elem[i]) !== false && elem[i].length === 1){
elem[i] = elem[i][0];
}
else if (elem[i].length > 1){
flatten(elem[i]);
} else if (!Array.isArray(elem[i])){
final.push(elem[i]);
}
}
return final;
}
var result = flatten(arr);
return flatten;
}
flattening([1, [2], [3, [[4]]]]);// should return [1, 2, 3, 4].