Created
June 22, 2012 21:42
-
-
Save noromanba/2975364 to your computer and use it in GitHub Desktop.
Greedy flatten function for Array in JavaScript via http://ptech.g.hatena.ne.jp/noromanba/20120622/1340396466
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
// flatten.js | |
// @author noromanba (https://www.hatena.ne.jp/noromanba/) | |
// @license Public Domain https://creativecommons.org/licenses/publicdomain/ | |
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/reduce | |
var flatten = function (ary) { | |
return ary.reduce(function (p, c) { | |
return Array.isArray(c) ? p.concat(flatten(c)) : p.concat(c); | |
}, []); | |
}; | |
// console.log(flatten([[[2], 0], [1, 3], [4, 6, [5, 7]]])); | |
// [2, 0, 1, 3, 4, 6, 5, 7] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment