eachSlice

eachSlice(size[, iterator = Prototype.K[, context]]) -> [slice...]

Groups items in chunks based on a given size, with last chunk being possibly smaller.

Sometimes, you want to cut collections into chunks. Roughly equal-sized. Maybe you want to put it into multiple columns, or some other stylish layout. Maybe you can only pass so many at a time to a back-end processing layer (aaaah, those hard-coded, arbitrary limits in legacy software… ). Maybe you just feel like it. Just use eachSlice or its fixed-size variant, inGroupsOf.

The optional context parameter is what the iterator function will be bound to. If used, the this keyword inside the iterator will point to the object given by the argument.

Example


var students = [
  { name: 'Sunny', age: 20 },  { name: 'Audrey', age: 21 },
  { name: 'Matt', age: 20 },   { name: '√Člodie', age: 26 },
  { name: 'Will', age: 21 },   { name: 'David', age: 23 },
  { name: 'Julien', age: 22 }, { name: 'Thomas', age: 21 },
  { name: 'Serpil', age: 22 }
];

students.eachSlice(4, function(toon) {
  return toon.pluck('name');
})
// -> [ ['Sunny', 'Audrey', 'Matt', '√Člodie'],
//      ['Will', 'David', 'Julien', 'Thomas'],
//      ['Serpil'] ]

students.eachSlice(2).first()
// -> [{ name: 'Sunny', age: 20 }, { name: 'Audrey', age: 21 }]

See also

A common use-case for eachSlice, which mandates fixed-size groups, thereby requiring padding of the last one if necessary, is available through inGroupsOf.