Skip to content

Instantly share code, notes, and snippets.

@chiragmongia
Last active June 1, 2016 12:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chiragmongia/0309e7b4ace09476fc3b5ca1f16819d7 to your computer and use it in GitHub Desktop.
Save chiragmongia/0309e7b4ace09476fc3b5ca1f16819d7 to your computer and use it in GitHub Desktop.
Javascript: flatten function on Array
// Defining flatten method on array
Array.prototype.flatten = function () {
var result = [];
(function arrayFlatten(arr) {
arr.forEach(function(element) {
element.constructor === Array ? arrayFlatten(element) : result.push(element);
})
})(this);
return result;
};
// Examples
var arr = [1, [2, 3], [4, 5], [6, 7, 8]];
arr.flatten(); // [1, 2, 3, 4, 5, 6, 7, 8]
arr = [1, [2, 3, [4, 5, [6, 7]]], [8], [9, 10]]
arr.flatten(); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment