hatched
hatched

Reputation: 865

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. Please help. Thanks!

Upvotes: 0

Views: 53

Answers (1)

Robby Cornelissen
Robby Cornelissen

Reputation: 97130

You could use a simple reduce() operation that keeps track of the current value you're basing your grouping on:

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);

Upvotes: 1

Related Questions