Skip to content

Latest commit

 

History

History
31 lines (20 loc) · 879 Bytes

451.md

File metadata and controls

31 lines (20 loc) · 879 Bytes

实现一个数组扁平化的函数 flatten

::: tip Issue 欢迎在 Issue 中交流与讨论: Issue 451 :::

::: tip Author 回答者: shfshanyue :::

在 ES2019 之前,可通过 reduce + concat 实现,由于 Array.prototype.concat 既可以连接数组又可以连接单项,十分巧妙

const flatten = list => list.reduce( (a, b) => a.concat(b), [])

一个更简单的实现方式是 Array.prototype.concat... 运算符

const flatten = list => [].concat(...list)

如果要求深层数组打平,则如下实现

const flatten = list => list.reduce((a, b) => a.concat(Array.isArray(b) ? flatten(b) : b), [])

在 ES2019 之后,可通过 Array.prototype.flat 直接实现!