[英]Split array into evenly sized arrays
I need to split an array into 3 even arrays.我需要将一个数组分成 3 个偶数 arrays。 So far I have only found examples of chunking into specified array lengths.到目前为止,我只找到了分块到指定数组长度的示例。 For example:例如:
var array = [1,2,3,4,5];
const results = [];
while (array.length) {
results.push(array.splice(0, 3));
}
return results; //returns [1,2,3],[4,5]
So if i had array = [1,2,3,4,5]
(or any other length)所以如果我有array = [1,2,3,4,5]
(或任何其他长度)
I need to split this into [1,2], [3,4], [5]
我需要将其拆分为[1,2], [3,4], [5]
Any ideas?有任何想法吗?
Figure out the size of the chunks by dividing the length by 3:通过将长度除以 3 来计算块的大小:
var array = [1,2,3,4,5]; const results = []; const chunkSize = Math.ceil(array.length / 3); while (array.length) { results.push(array.splice(0, chunkSize)); } console.log(results);
You could slice the array and use a size for adding the wanted lengths.您可以对数组进行切片并使用大小来添加所需的长度。
This approach does not mutate the given data.这种方法不会改变给定的数据。
var array = [1, 2, 3, 4, 5], results = [], size = Math.ceil(array.length / 3), i = 0; while (i < array.length) results.push(array.slice(i, i += size)); console.log(results);
.as-console-wrapper { max-height: 100%;important: top; 0; }
Try out this in this you need to provide the number of a chunk试试这个在这个你需要提供一个块的数量
const arr = [1,2,3,4,5]; const chunk = (input, nos) => { let size = Math.ceil(input.length/nos); return input.reduce((arr, item, idx) => { return idx % size === 0? [...arr, [item]]: [...arr.slice(0, -1), [...arr.slice(-1)[0], item]]; }, []); }; console.log(chunk(arr, 3));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.