本文介绍了将数组拆分为长度为 N 的块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to split an array (which has 10 items) into 4 chunks, which contain a maximum of n items.

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

然后打印:

['a', 'b', 'c']
['d', 'e', 'f']
['j', 'h', 'i']
['j']

以上假设 n = 3,但是值应该是动态的.

The above assumes n = 3, however, the value should be dynamic.

谢谢

推荐答案

可能是这样的:

var a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];

var arrays = [], size = 3;

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

console.log(arrays);

参见 splice Array 的方法.

See splice Array's method.

另一种不改变数组的方法,除了在分块之前创建它的浅拷贝,可以使用 slice 和 for... 循环:

An alternative method that does not mutate the array, beside create a shallow copy of it before chunk it, could be done by using slice and a for…loop:

var a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];

var arrays = [], size = 3;

for (let i = 0; i < a.length; i += size)
   arrays.push(a.slice(i, i + size));

console.log(arrays);

虽然更面向函数式编程的方法可能是:

While a more functional programming oriented approach, could be:

const chunks = (a, size) =>
    Array.from(
        new Array(Math.ceil(a.length / size)),
        (_, i) => a.slice(i * size, i * size + size)
    );

let a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];

console.log(chunks(a, 3));
console.log(chunks(a, 2));

参见 Array.from 以及如何 new Array(n) 特别有效.

See Array.from and how new Array(n) works, specifically.

这篇关于将数组拆分为长度为 N 的块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 12:06