how can I rewrite a push with a map by executing a slice?

Viewed 78

I would like to know if it is possible to change this push loop with a simple map.

the aim is to create chunks from an array of objects based on the number of columns and rows of a grid.

for example: if I have two rows and two columns the array of objects is divided into an array (chunks = []) in the following way:

 const row = 2;
 const col = 2;
 const pages = [
       {id:'one', name:'page_1', active:false},
       {id:'two', name:'page_2', active:false},
       {id:'three', name:'page_2', active:false},
       {id:'four', name:'page_4', active:false},
       {id:'five', name:'page_5', active:false},
    ]

"Chunks" should come this way:

 let chunks = [
   //grid 1 whit max col * row element
   [
       {id:'one', name:'page_1', active:false},
       {id:'two', name:'page_2', active:false},
       {id:'three', name:'page_2', active:false},
       {id:'four', name:'page_4', active:false},
   ],
  //grid 1 whit max col * row element
   [
       {id:'five', name:'page_5', active:false}, 
   ],
 ]

I have done it this way and this works well. But I wonder if it's possible to edit and improve everything using only a map instead of a push.

    const pages = [
       {id:'one', name:'page_1', active:false},
       {id:'two', name:'page_2', active:false},
       {id:'three', name:'page_2', active:false},
       {id:'four', name:'page_4', active:false},
       {id:'five', name:'page_5', active:false},
    ]
    const row = 2;
    const col = 2;
    let rowIndex = 0;
    let chunkIndex = 0;
    let chunks = [];
    while (row !== rowIndex) {
      chunks.push(page.slice(chunkIndex, chunkIndex + col));
      chunkIndex += col;
      rowIndex += 1;
    }
0 Answers
Related