Last active
November 9, 2016 01:39
-
-
Save pedrojimenezp/f9d8306505a2d72a7b37e1ac992945af to your computer and use it in GitHub Desktop.
Function that takes an array of arbitrarily nested arrays and returns a 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
// this function takes an array and return a flattened array | |
function flatten(array) { | |
// Iterates over the given array to return just one flatten array | |
return array.reduce((newArray, item) => { | |
// Check if the item to add is an array itself to call the function again to make the item a flatten array | |
if (item.constructor === Array) return newArray.concat(flatten(item)); | |
// If is not an array just adds the item to the new array | |
return newArray.concat(item); | |
}, []); | |
} | |
// Some tests | |
const a = flatten([1,2,[3,4,5],[6,7,[8,[9,10,11,12,13,14,[15,16,17,[18,19,[20]]]]]]]); | |
const b = flatten([[1,2,[3]],4]); | |
const c = flatten([["1","2",["3"]],"4"]); | |
const d = flatten([[{"1":1},{"2":2},[{"3":3}]],{"4":4}]); | |
const e = flatten([1,2,[3,4,5],[6,7,[8,[9,10,11,12,13,14,[15,16,17,[18,19,[20,[["1","2",["3"]],"4",[[{"1":1},{"2":2},[{"3":3}]],{"4":4}]]]]]]]]]) | |
console.log(a); | |
console.log(b); | |
console.log(c); | |
console.log(d); | |
console.log(e); | |
//Copy and paste on some browsers console or <script> tag and see the results |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment