将数组拆分为N长度的块

mrd*_*iri 83 javascript arrays

如何将一个数组(有10个项目)拆分为4个包含最多n项目的块.

var a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];
//a function splits it to four arrays.
console.log(b, c, d, e);
Run Code Online (Sandbox Code Playgroud)

它打印:

['a', 'b', 'c']
['d', 'e', 'f']
['j', 'h', 'i']
['j']
Run Code Online (Sandbox Code Playgroud)

n = 3但是,上述假定值应该是动态的.

谢谢

ZER*_*ER0 182

它可能是这样的:

var arrays = [], size = 3;

while (a.length > 0)
    arrays.push(a.splice(0, size));

console.log(arrays);
Run Code Online (Sandbox Code Playgroud)

请参阅splice Array的方法.

  • 值得注意的是,这个方法_mutates_旧数组. (15认同)
  • 定义“更好”。这是我所知道的完成要求的最简单的方法。如果您不想改变原始数组,您可以对其进行浅拷贝。 (2认同)

Mir*_*dil 67

也许这段代码有帮助:

var chunk_size = 10;
var arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17];
var groups = arr.map( function(e,i){ 
     return i%chunk_size===0 ? arr.slice(i,i+chunk_size) : null; 
}).filter(function(e){ return e; });
console.log({arr, groups})
Run Code Online (Sandbox Code Playgroud)

  • 我喜欢你的解决方案.我清理了一下,把它变成了JS Bin.谢谢!http://jsbin.com/dokivomuzake/1/edit?js,console (6认同)
  • `const partitionArray = (array, size) => array.map( (e,i) => (i % size === 0) ? array.slice(i, i + size) : null ) .filter( (e ) => e )` (5认同)
  • 在`map`中你可以使用`return i%chunk_size === 0 && arr.slice(i,i + chunk_size)来简化它. (2认同)
  • @Buts-[`map`](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/map)遍历数组的每个元素。 (2认同)