Created
July 5, 2018 16:57
-
-
Save wangziling/75b645e842867f2c400822ef8c467683 to your computer and use it in GitHub Desktop.
Use es6 method - Generator, to flatten multidimensional 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
// method | |
const flat = function *(arr) { | |
const {length} = arr; | |
for(let i = 0; i< length; i++) { | |
const item = arr[i]; | |
if(Array.isArray(item)){ | |
yield* flat(item); | |
} else { | |
yield item; | |
} | |
} | |
} | |
// main | |
const flatten = function (arr) { | |
return [...flat(arr)]; | |
} | |
// try | |
const array = [1, [[2, ['a', 'b', ['c', ['d']]], 3], 4], [5, 6]]; | |
console.log(flatten(array)); // [1, 2, "a", "b", "c", "d", 3, 4, 5, 6] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment