-2

I tried my best to scavenge around on Stack Overflow and the internet in general to find a solution to the thing I'm building, but unfortunately could not find any way to solve my issue.

I have an array which can vary in size:

this.data = [
            { icon:'icon1.png', audio:'audio1.mp3', id:'id1', name: 'name1'},
            { icon:'icon2.png', audio:'audio2.mp3', id:'id2', name: 'name2'},
            { icon:'icon3.png', audio:'audio3.mp3', id:'id3', name: 'name3'},
            { icon:'icon4.png', audio:'audio4.mp3', id:'id4', name: 'name4'},
            { icon:'icon5.png', audio:'audio5.mp3', id:'id5', name: 'name5'},
            { icon:'icon6.png', audio:'audio6.mp3', id:'id6', name: 'name6'},
            { icon:'icon7.png', audio:'audio7.mp3', id:'id7', name: 'name7'},
            { icon:'icon8.png', audio:'audio8.mp3', id:'id8', name: 'name8'},
            { icon:'icon9.png', audio:'audio9.mp3', id:'id9', name: 'name9'},
            { icon:'icon10.png', audio:'audio10.mp3', id:'id10', name: 'name10'},
            { icon:'icon11.png', audio:'audio11.mp3', id:'id11', name: 'name11'},
            { icon:'icon12.png', audio:'audio12.mp3', id:'id12', name: 'name12'} ]

So I want to split this array into multiple smaller arrays, giving it a specific length. If it can't be split in equal lengths then the final array should just contain the remainder of elements. I achieved this by doing so:

var chunksize = 4;
var chunks = [];

this.data.forEach((item)=>{
  if(!chunks.length || chunks[chunks.length-1].length == chunksize)
      chunks.push([]);

      chunks[chunks.length-1].push(item);
 });

Now I have an array of arrays. But then I would like to put these smaller arrays (chunks) in another array. But I want to insert each array within chunks separately in this new array dynamically.

Like so:

this.pages = [chunks[0], chunks[1], chunks[2]];

I tried doing it with a for loop, but I couldn't figure it out.

halfer
  • 19,824
  • 17
  • 99
  • 186
Harry
  • 31
  • 1
  • 3

2 Answers2

0

Why not just assing chunks?

chunks' length is 3, just exactly the wanted length for pages.

this.pages = chunks;
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • I think I stared myself blind on what I wanted to achieve. This solved my problem instantly. Thanks so much! – Harry May 12 '18 at 14:55
0

Use chunk function from lodash library. Creates an array of elements split into groups the length of size. If array can't be split evenly, the final chunk will be the remaining elements.

exa) _.chunk(array, [size=2]) // it will create an arrays of length 2.

https://lodash.com/docs/4.17.10#chunk

Achu
  • 272
  • 2
  • 10