Last active
June 1, 2016 12:22
-
-
Save chiragmongia/0309e7b4ace09476fc3b5ca1f16819d7 to your computer and use it in GitHub Desktop.
Javascript: flatten function on Array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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