0

sorry I don't speak English very well.

I have a table with several elements, I want to return all the X elements a new table inside a table.

For example:

let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
let newArr = [
[1,2,3],
[4,5,6],
[7,8,9],
[10,11,12],
];

This is the way I am currently doing this :

const size = shuffleImages.length / 4

while (shuffleImages.length > 0) {
 columns.push(shuffleImages.splice(0, size))
}

I would like to understand how to do this without using while and instead use for example .map or is there just an easier way to do this?

Shads
  • 11
  • 2

1 Answers1

0

You need to split the array into small array using map and than slice it :

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];

var chunkSize = 3;

const groups =  arr.map( function(e,i){ 
     return i%chunkSize===0 ? arr.slice(i,i+chunkSize) : null; 
}).filter((e) =>e);

console.log(groups);
Amit Baranes
  • 7,398
  • 2
  • 31
  • 53