Flatten a multidimensional array (Helper)

Array.prototype.flatten = function() { var flattened = []; function flatten(list) { list.forEach(function(item) { if (Array.isArray(item)) { flatten(item); } else { flattened.push(item); } // End of recursion }); // End of Array exploration } // End of inner method flatten(this); return flattened; }; // End of Flatten function // USE CASE //------------ var arr = ["lol", [4, 5, {}, ["some", true]], 90, null, [2, [9, 21], "flat"]]; console.log(arr.flatten()); // Outputs -> "["lol", 4, 5, {}, "some", true, 90, null, 2, 9, 21, "flat"]""
Helper function to flatten all sub-arrays inside an array ─ This snippet is a piece of a JavaScript library I'm working on, you can see it here: https://github.com/luishendrix92/WindowbirdJS

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.