让我们说我有一个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个元素?
当前回答
使用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提到这件事。
其他回答
打印稿版本。演示了将101个随机uid分成10个组
const idArrayLengthLimit = 10;
const randomOneHundredOneIdArray = Array
.from(Array(101).keys())
.map(() => generateUid(5));
function generateUid(length: number) {
const uidString: string[] = [];
const uidChars = 'abcdefghijklmnopqrstuvwxyz0123456789';
for (let i = 0; i < length; i++) {
uidString
.push(uidChars.charAt(Math.floor(Math.random() * uidChars.length)));
}
return uidString.join('');
}
for (let i = 0; i < randomOneHundredOneIdArray.length; i++) {
if(i % idArrayLengthLimit === 0){
const result = randomOneHundredOneIdArray
.filter((_,id) => id >= i && id < i + idArrayLengthLimit);
// Observe result
console.log(result);
}
}
我试过递归函数…
const chunk = (arr, n) =>
arr.length ? [arr.slice(0, n), ...chunk(arr.slice(n), n)] : [];
……这很好,很短,但似乎是@AymKdn回答1000个元素用时的256倍,10000个元素用时的1058倍!
使用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提到这件事。
下面是一个例子,我将一个数组分割成2个元素的块,只需从数组中拼接块,直到原始数组为空。 Const数组= [86,133,87,133,88,133,89,133,90,133]; Const new_array = []; Const chunksize = 2; While (array.length) { Const chunk = array.splice(0,chunksize); new_array.push(块); } console.log (new_array)
这是一个带有尾递归和数组解构的版本。
远非最快的性能,但我只是觉得好笑,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]]