让我们说我有一个Javascript数组看起来如下:

["Element 1","Element 2","Element 3",...]; // with close to a hundred elements.

什么样的方法适合将数组分成许多更小的数组,假设最多有10个元素?


当前回答

我更喜欢使用拼接法而不是切片法。 这个解决方案使用数组长度和块大小来创建循环计数,然后循环遍历数组,在每个步骤中由于拼接而在每个操作后变得更小。

    function chunk(array, size) {
      let resultArray = [];
      let chunkSize = array.length/size;
      for(i=0; i<chunkSize; i++) {
        resultArray.push(array.splice(0, size));
      }
    return console.log(resultArray);
    }
    chunk([1,2,3,4,5,6,7,8], 2);

如果不想改变原始数组,可以使用展开操作符克隆原始数组,然后使用该数组来解决问题。

    let clonedArray = [...OriginalArray]

其他回答

整洁干净,易于理解

 let nums = [1, 2, 3, 4, 5, 6, 7, 8, 9];
 let len = nums.length ;

    const chunkArr = (arr, chunkNo) => {
      let newArr = [];
      for(let i = 0; i < len; i++){
        if(nums[0] !== "" && nums[0] !== undefined ){
          let a = nums.splice(0,chunkNo) ; 
          newArr.push(a);
        }
      }
       return newArr ;
    }
    console.log(chunkArr(nums, 5));

ES6传播功能#ohmy #ftw

Const chunk = (size, xs) => xs.reduce ( (segments, _, index) => 索引%大小=== 0 ? […段,x。Slice (index, index + size)] 段, [] ); console.log(块(3,(1,2,3,4,5,6,7,8)));

最有效的方法是将数组视为Iterable,并进行惰性分页。这样,它将只在请求时生成数据。下面的代码使用了iter-ops库中的操作符页:

import {pipe, page} from 'iter-ops';

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]; // some input data

const i = pipe(arr, page(2)); //=> Iterable<number>

console.log(...i); //=> [ 1, 2 ] [ 3, 4 ] [ 5, 6 ] [ 7, 8 ] [ 9 ]

工作方式与任何Iterable或AsyncIterable相同。


附:我是图书馆的作者。

这是一个递归的解决方案,尾部调用优化。

const splitEvery = (n, xs, y=[]) => xs。长度= = = 0 ?y: splitEvery(n, xs.slice(n), y.concat([xs. slice(n)])片(0,n)))) console.log(splitEvery(2, [0,1,2,3,4,5,6,7,8,9]))

我是这样解决的:

const chunks = [];
const chunkSize = 10;
for (let i = 0; i < arrayToSplit.length; i += chunkSize) {
  const tempArray = arrayToSplit.slice(i, i + chunkSize);
  chunks.push(tempArray);
}