Skip to content
Advertisement

convert single array by two dimensional array by 6

I am trying to convert and merge my single array to two dimensional array. I use map for that but I can’t achieve the output I want. May I ask any suggestion on how to achieve this?

The data is below:

          var singelArr = ['a','b','c','d','e','f','a','b','c','d','e','f','a','b','c','d','e','f'];

          var doubleArr = [
                                ['','','','','',''],
                                ['','','','','',''],
                                ['','','','','',''],
                                ['','','','','',''],
                                ['','','','','',''],

                          ]

And now my expected output is:

 output = [
           ['a','b','c','d','e','f'],
           ['b','c','d','e','a','f'],
           ['b','c','d','e','a','f'],
           ['','','','','',''],
           ['','','','','','']

 ]; 

What I’ve done so far is https://jsfiddle.net/jc3v25bs/. I can display the data element by 6 but the problem is I am not sure how can I merge it to my doubleArr variable. I also prefer something that it will loop faster.

Any idea is much appreciated. Thank you.

Advertisement

Answer

You can use the slice() function to split the first array. Then you could create your output by concatenating the result with the last part of the second array.

let singleArr = ['a','b','c','d','e','f','a','b','c','d','e','f','a','b','c','d','e','f'];

let doubleArr = [
  ['','','','','',''],
  ['','','','','',''],
  ['','','','','',''],
  ['','','','','',''],
  ['','','','','',''],

];

let chunkedArr = [];
for(i=0,j=0; i<singleArr.length; i+=6, j++){
    chunkedArr[j] = singleArr.slice(i, i+6);
}
let output = chunkedArr.concat(doubleArr.slice(chunkedArr.length));

console.log(output);
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement