We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
const normalFlatten = (arr: any[]): any[] => { var res = [] for(let i = 0; i < arr.length; i++){ let item = arr[i] if(Array.isArray(item)) { res.push(...normalFlatten(item)) } else { res.push(item) } } return res }
—————————————————————————————————————————— 2. 通过 reduce + 递归方式
const recursiveFlattening = (arr: any[]): any => { return arr.reduce( (acc, curVal) => { return Array.isArray(curVal) ? acc.concat(recursiveFlattening(curVal)) : acc.concat(curVal) }, [] ); }
—————————————————————————————————————————— 3. 用非递归的方式(使用栈)
const arrayFlattening = (arr: any[]): any[] => { const stack = [...arr]; const res = []; while(stack.length) { const head = stack.shift(); if (Array.isArray(head)) { stack.unshift(...head); } else { res.push(head); } } return res.reverse(); }
—————————————————————————————————————————— 4. 利用 ES6 解构的特性,逐层解构
const awesomeFlatten = (arr: any[]) => { while(arr.some(item => Array.isArray(item))){ console.log(arr) arr = [].concat(...arr) } return arr }
—————————————————————————————————————————— 5. 针对数字类型数组,可以通过 join 和 split 方法即可完成
const numbersFlattening = (arr: number[]): number[] => { return arr.join(',').split(',').map(num => Number(num)) }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
——————————————————————————————————————————
2. 通过 reduce + 递归方式
——————————————————————————————————————————
3. 用非递归的方式(使用栈)
——————————————————————————————————————————
4. 利用 ES6 解构的特性,逐层解构
——————————————————————————————————————————
5. 针对数字类型数组,可以通过 join 和 split 方法即可完成
The text was updated successfully, but these errors were encountered: