简体   繁体   English

javascript - 从另一个多维数组创建多维数组

[英]javascript - create multidimensional array from another multidimensional array

I need to generate a multidimensional array from a multidimensional array.我需要从多维数组生成多维数组。
For example, my array:例如,我的数组:

var codes = [

['2', '12521'],
['3', '32344'],
['3', '35213'],
['4', '42312'],
['4', '41122'],
['5', '51111']

];

And my new array should have this structure:我的新数组应该有这样的结构:

[0] => Array
    (
        [0] => Array
            (
               [0] => '2'
               [1] => '12521'
            }
    )  
[1] => Array
    (
        [0] => Array
            (
               [0] => '3'
               [1] => '32344'
            }
        [1] => Array
            (
               [0] => '3'
               [1] => '35213'
            }
    )  
[2] => Array
    (
        [0] => Array
            (
               [0] => '4'
               [1] => '42312'
            }
        [1] => Array
            (
               [0] => '4'
               [1] => '41122'
            }
    )  
...

I have been trying to use for looping to populate the new array but have been struggling to do it.我一直在尝试使用for循环来填充新数组,但一直在努力做到这一点。 Please help.请帮忙。 Thanks!谢谢!

You could use a simple reduce() operation that keeps track of the current value you're basing your grouping on:您可以使用一个简单的reduce()操作来跟踪您分组所基于的当前值:

 const codes = [ ['2', '12521'], ['3', '32344'], ['3', '35213'], ['4', '42312'], ['4', '41122'], ['5', '51111', ''] ]; const output = codes.reduce(({result, current}, [x, ...y]) => { if (current.== x) result;push([]). result[result.length - 1],push([x. ..;y]), return {result: current; x}, }: {result. []});result. console;log(output);

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

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