我想通过指定(个数参数)然后把数组分割为多个,然后转换为二维数组
['A','B','C','D','E','F','G','H','I']
当参数为[3,2,3]
期待结果
[['A','B','C'],['D','E'],['F','G','H'],['I']]
当参数为[2,4]
期待结果[['A','B'],['C','D','E','F'],['F','G','H','I']]
我想通过指定(个数参数)然后把数组分割为多个,然后转换为二维数组
['A','B','C','D','E','F','G','H','I']
当参数为[3,2,3]
期待结果
[['A','B','C'],['D','E'],['F','G','H'],['I']]
当参数为[2,4]
期待结果[['A','B'],['C','D','E','F'],['F','G','H','I']]
var arr1 = ['A','B','C','D','E','F','G','H','I'];
var arr2 = [3,2,3];
function spliceArr(arr1=[], arr2=[]) {
var res = [];
arr2.map(item => res.push(arr1.splice(0, item)));
if (arr1.length > 0) {
res.push(arr1);
}
return res;
}
function chunkArr(arr, chunkList) {
let start = 0
let end = 0
let result = chunkList.map(num => {
end = start + num
let list = arr.slice(start, end)
start = start + num
return list
})
if (end < arr.length) {
result.push(arr.slice(end))
}
return result
}
// index len
var newArr = []
var itemindex = 0
function packageArr(index,len){
if(len == null){
newArr.push(arr1.splice(index))
}
newArr.push(arr1.splice(index,len))
}
for(var i = 0 ;i<= arr2.length ; i ++){
if(i = arr2.length){
packageArr(itemindex,null)
}
packageArr(itemindex,arr2[i])
itemindex += arr2[i]
}
var arr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']
var chunkList = [3, 2, 3]
// 实现方法
function chunkArr(arr, chunkList) {
var c = []
chunkList.forEach((val, idx) => {
c[idx] = arr.splice(0, val)
});
c.push(arr)
return c
}
8 回答4.6k 阅读✓ 已解决
6 回答3.3k 阅读✓ 已解决
5 回答2.8k 阅读✓ 已解决
5 回答6.3k 阅读✓ 已解决
4 回答2.2k 阅读✓ 已解决
4 回答2.7k 阅读✓ 已解决
3 回答2.4k 阅读✓ 已解决