2

i need some help manipulating/paginating a JS array object by 5:

var musicItems = [
    ["assets/audio/1.wav"],
    ["assets/audio/2.wav"],
    ["assets/audio/3.wav"],
    ["assets/audio/4.wav"],
    ["assets/audio/5.wav"],
    ["assets/audio/6.wav"],
    ["assets/audio/7.wav"],
    ["assets/audio/8.wav"],
];

I want to know in JS the number of sets (2) and which elements belong to which set (set1->1-5, set2->6-8). Appreciate any help.

EDIT I am looking to do something like Split array into chunks

But as you can see, my array is different.

Community
  • 1
  • 1
user2350858
  • 681
  • 2
  • 10
  • 16

2 Answers2

4

This is just a simple demo on how you could achieve this with the modulo operator %. There will be more efficient and smaller solutions.

var musicItems = [
    ["assets/audio/1.wav"],
    ["assets/audio/2.wav"],
    ["assets/audio/3.wav"],
    ["assets/audio/4.wav"],
    ["assets/audio/5.wav"],
    ["assets/audio/6.wav"],
    ["assets/audio/7.wav"],
    ["assets/audio/8.wav"],
];

var sets = new Object();
var set = new Array();
var setCounter = 0;

for(var i = 0; i < musicItems.length; i++) {
    set.push(musicItems[i]);

    if((i + 1) % 5 == 0 || (i + 1) >= musicItems.length) {
        setCounter++;
        sets['set' + setCounter] = set;
        set = new Array();
    }
}

console.log(sets['set1']);
console.log(sets['set2']);

Basically what this does is to iterate through the musicItems, with modulo % 5 we check if the current item can be devided by 5 without rest, so we know a set is complete as we collected 5 items. Then we add the set to the overall sets object to use it later on as a dictionary (as wished with 'set1', 'set2' etc.) and we clear the current set, to fill it with the next n-5 items.

Avinor
  • 846
  • 1
  • 8
  • 19
0

Bref :

  max=5,j=0;
  for(var i=0;i<musicItems.length;i=i+max){
        j++;
       sets['set' + j] = musicItems.offset(i).max(max);
  }

Explanation

Pagination concept rely on two parameters:

  1. Offset :
  2. Max :

Then :

musicItems.offset(0).max(5) ;   // 1st set
   // >  [ ["assets/audio/1.wav"],["assets/audio/2.wav"],["assets/audio/3.wav"],["assets/audio/4.wav"],["assets/audio/5.wav"]  ]
musicItems.offset(0+5).max(5) ;  // second set
   // >  [ ["assets/audio/6.wav"],["assets/audio/7.wav"],["assets/audio/8.wav"] ]

Required API :

Array.prototype.max = function(mx) {
   return this.filter(function(e,i){return i < mx;}); }
};

Array.prototype.offset=function(os){
   return this.filter(function(e,i){return i> os-1 });
 };
Abdennour TOUMI
  • 87,526
  • 38
  • 249
  • 254