Last active
August 29, 2015 14:06
-
-
Save GZShi/d5bd22cfe3b3247c2582 to your computer and use it in GitHub Desktop.
flatten 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
var flattenWithReduce = (function () { | |
function flatten(prev, curr, i, a) { | |
var result; | |
if(Array.isArray(curr)) { | |
result = prev.concat(curr.reduce(flatten, [])); | |
} else { | |
result = prev.concat(curr); | |
} | |
return result; | |
} | |
return function (array) { | |
if(!Array.isArray(array)) throw new TypeError("the first argument is not a Array"); | |
return array.reduce(flatten, []); | |
} | |
})(); | |
// 大同小异 | |
function flattenWithApply(array) { | |
if(!Array.isArray(array)) throw new TypeError("the first argument is not a Array"); | |
var result = []; | |
array.forEach(function (e, i, a) { | |
if(Array.isArray(e)) { | |
Array.prototype.push.apply(result, flattenWithApply(e)); | |
} else { | |
result.push(e); | |
} | |
}); | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment