简体   繁体   English

将嵌套数组拆分为 JavaScript 中的多个 arrays

[英]Splitting nested array to multiple arrays in JavaScript

I have an array like below.我有一个像下面这样的数组。

[[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6]]

and I want array like this.我想要这样的数组。

[[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]]

here is my approach to get this.这是我得到这个的方法。

chunk(result, size) {
    var finalResluts = result;    
    for(let j=0; j<result.length; j++){      
      var  k = 0, n = result[j].length;
        while (k < n) {
        finalResluts[j].push(result[j].slice(k, k += size));
        }
    }    
    return finalResluts;
}

console.log(chunk([[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6]], 3));

result showing as like below.结果显示如下。 what I am doing wrong here?我在这里做错了什么?

0: Array(8)
0: 1
1: 2
2: 3
3: 4
4: 5
5: 6
6: (3) [1, 2, 3]
7: (3) [4, 5, 6]

for reference here is stackblitz https://stackblitz.com/edit/typescript-rmzpby这里的参考是 stackblitz https://stackblitz.com/edit/typescript-rmzpby

The problem is that you initialize your finalResults to the input array results , thus the results are pushed into the original [1, 2, 3, 4, 5, 6] array.问题是您将finalResults初始化为输入数组results ,因此结果被推送到原始[1, 2, 3, 4, 5, 6]数组中。
What you need to do is create an empty array for each subArray of the input to populate later.您需要做的是为输入的每个子数组创建一个空数组,以便稍后填充。 Easiest to achieve with map function:使用map function 最容易实现:

function chunk(result, size) {
    //for each subArray - create empty array
    var finalResluts = result.map(subArray => []);    
    for(let j=0; j<result.length; j++){      
      var  k = 0, n = result[j].length;
        while (k < n) {
        finalResluts[j].push(result[j].slice(k, k += size));
        }
    }    
    return finalResluts;
}

console.log(chunk([[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6]], 3));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM