让我们说我有一个Javascript数组看起来如下:
["Element 1","Element 2","Element 3",...]; // with close to a hundred elements.
什么样的方法适合将数组分成许多更小的数组,假设最多有10个元素?
让我们说我有一个Javascript数组看起来如下:
["Element 1","Element 2","Element 3",...]; // with close to a hundred elements.
什么样的方法适合将数组分成许多更小的数组,假设最多有10个元素?
当前回答
编辑:@mblase75在我写我的答案时在前面的答案上添加了更简洁的代码,所以我建议使用他的解决方案。
你可以使用这样的代码:
var longArray = ["Element 1","Element 2","Element 3", /*...*/];
var smallerArrays = []; // will contain the sub-arrays of 10 elements each
var arraySize = 10;
for (var i=0;i<Math.ceil(longArray.length/arraySize);i++) {
smallerArrays.push(longArray.slice(i*arraySize,i*arraySize+arraySize));
}
修改arraySize的值可以改变较小数组的最大长度。
其他回答
一个有效的解决方案是通过indexChunk将解决方案与slice和push连接起来,解决方案被分割成块:
function splitChunks(sourceArray, chunkSize) { if(chunkSize <= 0) throw "chunkSize must be greater than 0"; let result = []; for (var i = 0; i < sourceArray.length; i += chunkSize) { result[i / chunkSize] = sourceArray.slice(i, i + chunkSize); } return result; } let ar1 = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 ]; console.log("Split in chunks with 4 size", splitChunks(ar1, 4)); console.log("Split in chunks with 7 size", splitChunks(ar1, 7));
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)));
我推荐使用lodash。分块是其中一个有用的功能。 产品说明:
npm i --save lodash
在你的项目中包括:
import * as _ from 'lodash';
用法:
const arrayOfElements = ["Element 1","Element 2","Element 3", "Element 4", "Element 5","Element 6","Element 7","Element 8","Element 9","Element 10","Element 11","Element 12"]
const chunkedElements = _.chunk(arrayOfElements, 10)
你可以在这里找到我的样本: https://playcode.io/659171/
使用array .prototype.splice()并拼接它,直到数组有元素。
Array.prototype.chunk = function(size) { Let result = []; 而(this.length) { result.push(这一点。拼接(0,大小)); } 返回结果; } Const arr = [1,2,3,4,5,6,7,8,9]; console.log (arr.chunk (2));
更新
array .prototype.splice()填充原始数组,在执行chunk()之后,原始数组(arr)变成[]。
如果你想保持原始数组不变,那就复制arr数据到另一个数组,然后做同样的事情。
Array.prototype.chunk = function(size) { Let data =[…this]; Let result = []; 而(data.length) { result.push(数据。拼接(0,大小)); } 返回结果; } Const arr = [1,2,3,4,5,6,7,8,9]; console.log(分块:,arr.chunk (2)); console.log(“原始”,arr);
附注:感谢@mts-knn提到这件事。
这里有一个更具体的案例,有人可能会觉得有价值。我还没看到这里提到过。
如果你不想要固定/均匀的数据块大小,而是想要指定拆分数组的下标怎么办?在这种情况下,你可以使用这个:
const splitArray = (array = [], splits = []) => {
array = [...array]; // make shallow copy to avoid mutating original
const chunks = []; // collect chunks
for (const split of splits.reverse()) chunks.push(array.splice(split)); // go backwards through split indices and lop off end of array
chunks.push(array); // add last remaining chunk (at beginning of array)
return chunks.reverse(); // restore chunk order
};
然后:
splitArray([1, 2, 3, 4, 5, 6, 7, 8, 9], [4, 6])
// [ [1, 2, 3, 4] , [5, 6] , [7, 8, 9] ]
请注意,如果你给它非升序/重复/负/非整数/等分割索引,这将会发生有趣的事情。您可以为这些边缘情况添加检查(例如array .from(new Set(array))来消除重复。