Last active
September 2, 2019 20:04
-
-
Save haikelfazzani/ed67f820d700723526ce25c7b4510398 to your computer and use it in GitHub Desktop.
flat 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
// 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