[英]Split an Array with specific chunks size
For example I have a chunks array, this array has the sizes of individual chunks.例如我有一个块数组,这个数组有各个块的大小。
let example = [3,3]; // Chunks array
let auxarrayindex = [1,2,3,4,5,6]; // Array that I want to splice
let example2 = [3,2,3]; // Chunks array
let auxarrayindex2 = [1,2,3,4,5,6,7,8]; // Array that I want to splice
The result that I want is:我想要的结果是:
[1,2,3],[4,5,6] and the second [1,2,3],[4,5],[6,7,8]
This is my code:这是我的代码:
for (let auxexample = 0; auxexample < example.length; auxexample++) {
finalauxarray.push(auxarrayindex.slice(0, example[auxexample]));
}
The result from my code is:我的代码的结果是:
[1,2,3],[1,2,3] and the second [1,2,3],[1,2],[1,2,3]
The problem is that your slice always starts at the same index (0).问题是您的切片总是从相同的索引 (0) 开始。
Use a variable (like i
) that you increase as you take chunks:使用在获取块时增加的变量(如
i
):
let example = [3,2,3]; let auxarrayindex = [1,2,3,4,5,6,7,8]; let finalauxarray = []; let i = 0; for (let auxexample = 0; auxexample < example.length; auxexample++) { finalauxarray.push(auxarrayindex.slice(i, i+=example[auxexample])); } console.log(finalauxarray);
You could also use map
for your loop:您还可以将
map
用于您的循环:
let example = [3,2,3]; let auxarrayindex = [1,2,3,4,5,6,7,8]; let i = 0; let finalauxarray = example.map(size => auxarrayindex.slice(i, i+=size)); console.log(finalauxarray);
The problem is because of the slice parameters are wrong You can learn more about how slice works on this link问题是因为切片参数错误您可以在此链接上了解有关切片如何工作的更多信息
https://www.w3schools.com/jsref/jsref_slice_array.asp https://www.w3schools.com/jsref/jsref_slice_array.asp
It takes as first parameter the starti g position and as last parameter the ending position which is not included in the result它将 starti g position 作为第一个参数,将不包含在结果中的结尾 position 作为最后一个参数
You can aslo use splice for this as well https://www.w3schools.com/jsref/jsref_splice.asp您也可以为此使用拼接https://www.w3schools.com/jsref/jsref_splice.asp
Hope that helps希望有帮助
Working example using splice
instead of slice
as I think it offers a slightly cleaner API for this particular use-case:使用
splice
而不是slice
的工作示例,因为我认为它为这个特定的用例提供了一个稍微干净的 API:
let example = [3, 3]; let auxArrayIndex = [1, 2, 3, 4, 5, 6]; let example2 = [3, 2, 3]; let auxArrayIndex2 = [1, 2, 3, 4, 5, 6, 7, 8]; function getChunks(chunkSizes, array) { let result = []; for (let chunkSize of chunkSizes) { result.push(array.splice(0, chunkSize)); } return result; } let chunks = getChunks(example, auxArrayIndex); let chunks2 = getChunks(example2, auxArrayIndex2); console.log(chunks); // logs "[1,2,3], [4,5,6]" console.log(chunks2); // logs "[1,2,3], [4,5], [6,7,8]"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.