方法一: 平铺到一个新数组后,再去分组组合成新数组
var arr = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], ]; function fn(arr){ let len; let ary =[]; arr.forEach((x,index)=>{ arr.forEach((item) => { len = item.length; len--; ary.push(item[index]) }); }) return ary; } let getArr = fn(arr); console.log(getArr); // 分组逻辑 function resFn(arr){ let newArr= []; if(arr.length%3===0){ let count = arr.length/3; // arr.slice(0,i) // arr.slice(i,i*2); // arr.slice(i*2,i*3) for(var i=0;i<count; i++){ if(i==0){ newArr.unshift(arr.slice(i,count)); }else{ // 3,3*2 -> 3 6 // 3,3*3 -> 3 9 newArr.unshift(arr.slice(count*i,count*(i+1))) } } } return newArr; } var result = resFn(getArr) console.log(result);
方法二:双循环
var arr = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], ]; function fn(arr){ let num = arr.length; let r =[]; let r1 =[]; for(let i=0;i<num;i++){ r1=[]; for(let j=0;j<arr.length;j++){ r1.push(arr[j][i]) } r.unshift(r1) } return r; } let getArr = fn(arr); console.log(getArr);
方法三:递归
var arr = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], ]; function outerFn(arr,index=0){ let r =[]; function fn(arr,index=0){ let temp = []; for(let i=0;i<arr.length;i++){ // console.log(arr[i][index]); temp.push(arr[i][index]) } r.unshift(temp); if(index < arr.length-1){ index++; fn(arr,index) } } fn(arr); return r; } let getArr = outerFn(arr); // getArr.reverse(); console.log(getArr);