【数组】将一个数组分成多个数组(或数组中指定字段进行拆分)

文章展示了如何使用JavaScript将一个数组分成多个子数组,以及如何按指定字段对数组元素进行拼接。提供了两个函数,第一个函数`group`用于按指定长度切分数组,第二个函数`groupArr`则用于将数组中特定字段(如uuid)每3个一组拼接成新的数组。
摘要由CSDN通过智能技术生成

将一个数组分成多个数组(或数组中指定字段进行拆分)

要处理的目标数据

let data = [
    { name: 'Liming', uuid: '1' },
    { name: 'Liming', uuid: '2' },
    { name: 'Liming', uuid: '3' },
    { name: 'Liming', uuid: '4' },
    { name: 'Liming', uuid: '5' },
    { name: 'Liming', uuid: '6' },
    { name: 'Liming', uuid: '7' },
    { name: 'Liming', uuid: '8' },
    { name: 'Liming', uuid: '9' },
    { name: 'Liming', uuid: '10' },
]

1. 将一个数组分成多个数组

 group = (array = [], subGroupLength = 0) => {
   let index = 0;
   const newArray = [];
   while (index < array.length) {
     newArray.push(array.slice(index, index += subGroupLength));
   }
   return newArray;
 }
 console.log(group(data, 3))

结果
在这里插入图片描述

2. 数组中指定字段进行拆分

// 方法二  (数组指定字段字符串拼接)
groupArr = (array = [], subGroupLength = 0) => {
    const uuidSubArr = []
    let uuidStr = ''
    array.map((item, index) => {
        if (index % 3 === 0) {
            if (index > 0) {
                uuidSubArr.push(uuidStr)
            }
            uuidStr = item.uuid
        } else {
            uuidStr = `${uuidStr},${item.uuid}`
             if (index === (data.length - 1)) {
                uuidSubArr.push(uuidStr)
            }
        }
    })
    return uuidSubArr
}
console.log(groupArr(data, 3))

结果
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值