JS数组打平的三种方法

1.用迭代或者递归打平数组

ECMAScript在Array.prototype上增加了:两个方法flat(),flatMap()。
在没有这两个方法之前,打平数组就要用迭代或者递归的方法
如下示例:

function flatten(sourceArray, flattenedArray = []){
    for (const element of sourceArray) {
        if (Array.isArray(element)) {
            flatten(element, flattenedArray);
        } else {
            flattenedArray.push(element);
        }
    }
    return flattenedArray;
}

const arr = [[0], 1, 2, [3, [4, 5]], 6];
console.log(flatten(arr))
//[0, 1, 2, 3, 4, 5, 6]

但可选择打平到第几级就更好了(通过添加参数depth改写)

function flatten(sourceArray, depth, flattenedArray = []){
    for (const element of sourceArray) {
        if (Array.isArray(element) && depth > 0) {
            flatten(element, depth -1, flattenedArray);
        } else {
            flattenedArray.push(element);
        }
    }
    return flattenedArray;
}

const arr = [[0], 1, 2, [3, [4, 5]], 6];
console.log(flatten(arr,1))
//[0, 1, 2, 3, [4, 5], 6]

2.Array.prototype.flat(depth)打平数组

为了更规范,增加的Array.prototype.flat(depth)就可以实现上述功能

Array.prototype.flat(depth)接受一个depth参数,返回一个要打平Array实例的浅复制本。

const arr = [[0], 1, 2, [3, [4, 5]], 6];
console.log(arr.flat(2));
//[0, 1, 2, 3, 4, 5, 6]

3.Array.prototype.flatMap()打平数组

Array.prototype.flatMap()打平数组会执行一次映射操作,比Array.prototype.flat(depth)高效,浏览器之用执行一次遍历.
flatMap()的函数签名与map相同。例子如下:

const arr = [[1], [3], [5]];
console.log(arr.map([x] => [x, x+1]));
//[[1, 2], [3, 4], [5, 6]]

console.log(arr.flatMap([x] => [x, x+1]));
//[0, 1, 2, 3, [4, 5], 6]
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值