Skip to content

Instantly share code, notes, and snippets.

@GZShi
Last active August 29, 2015 14:06
Show Gist options
  • Save GZShi/d5bd22cfe3b3247c2582 to your computer and use it in GitHub Desktop.
Save GZShi/d5bd22cfe3b3247c2582 to your computer and use it in GitHub Desktop.
flatten array
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