将数组向上拼合到指定深度

5年以前  |  阅读数:377 次  |  编程语言:JavaScript 

将数组向上拼合到指定深度。

使用递归, 递减depth, 每层深度为1。使用Array.reduce()Array.concat()来合并元素或数组。基本情况下, 对于等于1depth停止递归。省略第二个元素,depth仅拼合到1的深度 (单个拼合)。

const flattenDepth = (arr, depth = 1) =>
depth != 1 ? arr.reduce((a, v) => a.concat(Array.isArray(v) ? flattenDepth(v, depth - 1) : v), [])
: arr.reduce((a, v) => a.concat(v), []);
// flattenDepth([1,[2],[[[3],4],5]], 2) -> [1,2,[3],4,5]

Copyright© 2013-2020

All Rights Reserved 京ICP备2023019179号-8