将一个数组分成多个数组(或数组中指定字段进行拆分)
要处理的目标数据
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))
结果