Let’s Chunk

var a = [1, 2, 3, 4, 5, 6, 7, 8];
var b = chunk(a, 2); // b = [[1, 2], [3, 4], [5, 6], [7, 8]]b = chunk(a, 3);     // b = [[1, 2, 3], [4, 5, 6], [7, 8]]b = chunk(a, 5)      // b = [[1, 2, 3, 4, 5], [6, 7, 8]]
function chunk(a, num) {   var res = [];   var i = 0;   while(i <= a.length — num) {      var chunk = Array(num);      for(var j = 0; j < num; j++)         chunk[j] = a[i + j];      res.push(chunk);      i += num;   }   if(i < a.length)      res.push(a.slice(i));   return res;}

--

--

I’m an academic and freelancer instructor, teaching computer science and software engineering for more than 17 years now.

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Shay Tavor

Shay Tavor

I’m an academic and freelancer instructor, teaching computer science and software engineering for more than 17 years now.