Skip to content

Instantly share code, notes, and snippets.

@haikelfazzani
Last active September 2, 2019 20:04
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 haikelfazzani/ed67f820d700723526ce25c7b4510398 to your computer and use it in GitHub Desktop.
Save haikelfazzani/ed67f820d700723526ce25c7b4510398 to your computer and use it in GitHub Desktop.
flat array
// flat single level array
arr1.reduce((acc, val) => acc.concat(val), []);
// deep level flatten
function flatDeep(arr1) {
return arr1.reduce((acc, val) => Array.isArray(val) ? acc.concat(flatDeep(val)) : acc.concat(val), []);
};
//recursive flatten deep
function flatten(array) {
var flattend = [];
(function flat(array) {
array.forEach(function(el) { Array.isArray(el) ? flat(el) : flattend.push(el) });
})(array);
return flattend;
}
// deep level flatten recursive (fastest)
function flatDeep(a, res) {
var i = 0, v;
for (; i < a.length; i++) {
v = a[i];
Array.isArray(v) ? flatDeep(v, res) : res.push(v);
}
return res;
}
// resource : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment