0

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!

5
  • "I have been trying to use for looping..." - You've forgotten to post the relevant code. Commented Nov 21, 2019 at 7:38
  • Is this just nesting each of the inner arrays into a new array, or am I misreading? Can you clarify? Commented Nov 21, 2019 at 7:43
  • @VLAZ They're grouped based on the first element in the 2-element arrays. Commented Nov 21, 2019 at 7:44
  • 1
    @RobbyCornelissen OK, this makes more sense. I find that expected representation hard to read. Commented Nov 21, 2019 at 7:45
  • @VLAZ it is based on the first element (single digit) of each arrays , such as 2,3,4,5 Commented Nov 21, 2019 at 7:45

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the solution! How do I modify the codes if I have more elements in each array of codes array ?
Updated the answer to allow for more elements.
I'm not sure why the output return me the exactly same row of array to me , my real data has 5 elements in a single array , such as ['R', '2' , '115' , 'AB' ,'117'],

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.