DamomHd / interview-question

整理各大厂面试题
1 stars 0 forks source link

实现反扁平化 输出指定N维数组 #5

Open DamomHd opened 4 years ago

DamomHd commented 4 years ago

执行output输出指定的N维数组

var arr = [1,2,3,4,5,6,7]

function output(){

}
output() 
//[[1,2],[3,4],[5,6],[7]]
//[[1,2,3],[4,5,6],[7]]
DamomHd commented 4 years ago
var list =[1,2,3,4,5,6,7]
function output(arr = [],deep = 2){
    var resultArr = []
    while(arr.length){
          resultArr.push(arr.splice(0,deep))
    }
    return resultArr
}
output(list,2)
DamomHd commented 4 years ago

@群友 Webster丶提供

const arr = [1, 2, 3, 4, 5, 6, 7];
const output = (ary = [], deep = 2) => {
    let itor = ary.slice(0, ary.length);
    let ret = [];
    while (itor.length) {
        ret = [...ret, itor.splice(0, deep)]
    }
    return ret;
}
DamomHd commented 4 years ago

@群友 jjzz闹 提供

function output(arr, deep){
    var res = [];
    res.push(arr.splice(0,deep));
    if(arr.length) res = res.concat(output(arr, deep));
    return res;
}