JS 数组如何指定分割?

我想通过指定(个数参数)然后把数组分割为多个,然后转换为二维数组

['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']]

阅读 2.2k
5 个回答
 let arr = ['A','B','C','D','E','F','G','H','I']
 let arr1 = [3,2,3]
 var fn = (arr, arr1) => [...arr1.map(v => arr.splice(0, v)), arr].filter(v => v.length)
 fn(arr, arr1)
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
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏