如何使用 ES6 方法动态创建二维数组?

How to create 2D array dynamically with the ES6 approach?

我一直在尝试使用函数从数组动态创建二维数组;但是,我无法摆脱 ES3 的老派方法。有人知道如何使用 ES6 方法重构以下代码吗?

const nums = [1,2,3,4,5,6,7,8,9,10,11,12];
const letters = ['a','b','c','d','e','f','g','h','i']; 

function create2D(arr,set) {
  const result = [];
  for (let i = 0; i < arr.length; i+=set) {
    const rows = arr.slice(i,i+set);
    result.push(rows);
  }
  return result;
}  

console.log(create2D(nums,4)); // [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ] ]
console.log(create2D(letters,3)); // [ [ 'a', 'b', 'c' ], [ 'd', 'e', 'f' ], [ 'g', 'h', 'i' ] ]

我只了解了“reduce”,无法找到如何从 for 循环中复制加法赋值“i+=set”。这是我目前所拥有的...

function create2D(arr,set) {
  return arr.reduce((result,item,i) => {
    result.push(arr.slice(i,i+set));
    return result;
  },[]);
}

console.log(create2D(nums, 4)); // [ [1, 2, 3, 4],[2, 3, 4, 5],[3, 4, 5, 6], ...]

你们非常接近。只需稍微修改一下:

const nums = [1,2,3,4,5,6,7,8,9,10,11,12];
const letters = ['a','b','c','d','e','f','g','h','i']; 

function create2D(arr,set) {
  return arr.reduce((result,item,i) => {
    let startVal = i*set //We want to jump through the startPoints. Not iterate through them all
    if (startVal < arr.length-1) { 
      result.push(arr.slice(startVal,startVal+set));
    }
    return result;
  }, []);
}

console.log(create2D(nums, 4)); // [ [1, 2, 3, 4],[2, 3, 4, 5],[3, 4, 5, 6], ...]

console.log(create2D(nums, 3));

console.log(create2D(letters, 3));