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

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

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


当前回答

嗨,试试这个——

 function split(arr, howMany) {
        var newArr = []; start = 0; end = howMany;
        for(var i=1; i<= Math.ceil(arr.length / howMany); i++) {
            newArr.push(arr.slice(start, end));
            start = start + howMany;
            end = end + howMany
        }
        console.log(newArr)
    }
    split([1,2,3,4,55,6,7,8,8,9],3)

其他回答

# in coffeescript
# assume "ar" is the original array
# newAr is the new array of arrays

newAr = []
chunk = 10
for i in [0... ar.length] by chunk
   newAr.push ar[i... i+chunk]

# or, print out the elements one line per chunk
for i in [0... ar.length] by chunk
   console.log ar[i... i+chunk].join ' '

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

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]))

下面是一个使用reduce的ES6版本

const perChunk = 2 //每个chunk有2个项目 const inputArray = ['a','b','c','d','e'] const result = inputArray。reduce((resultArray, item, index) => { const chunkIndex = Math.floor(index/perChunk) 如果(! resultArray [chunkIndex]) { resultArray[chunkIndex] =[] //启动一个新的chunk } resultArray [chunkIndex] .push(项) 返回resultArray }, []) console.log(结果);// result: [['a','b'], ['c','d'], ['e']]]

并且您已经准备好连接进一步的映射/缩减转换。 输入数组保持不变


如果你喜欢更短但可读性较差的版本,你可以在混合中添加一些concat,以获得相同的最终结果:

inputArray.reduce((all,one,i) => {
   const ch = Math.floor(i/perChunk); 
   all[ch] = [].concat((all[ch]||[]),one); 
   return all
}, [])

你可以使用余数运算符将连续的项放入不同的块中:

const ch = (i % perChunk); 

这是一个带有尾递归和数组解构的版本。

远非最快的性能,但我只是觉得好笑,js现在可以做到这一点。即使它没有为此进行优化:(

const getChunks = (arr, chunk_size, acc = []) => {
    if (arr.length === 0) { return acc }
    const [hd, tl] = [ arr.slice(0, chunk_size), arr.slice(chunk_size) ]
    return getChunks(tl, chunk_size, acc.concat([hd]))
}

// USAGE
const my_arr = [1,2,3,4,5,6,7,8,9]
const chunks = getChunks(my_arr, 2)
console.log(chunks) // [[1,2],[3,4], [5,6], [7,8], [9]]

这里是整洁和优化的实现chunk()函数。假设默认块大小为10。

var chunk = function(list, chunkSize) {
  if (!list.length) {
    return [];
  }
  if (typeof chunkSize === undefined) {
    chunkSize = 10;
  }

  var i, j, t, chunks = [];
  for (i = 0, j = list.length; i < j; i += chunkSize) {
    t = list.slice(i, i + chunkSize);
    chunks.push(t);
  }

  return chunks;
};

//calling function
var list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
var chunks = chunk(list);