Advertisement
Guest User

Untitled

a guest
Feb 26th, 2020
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * Chunks array into equally large sizes as far as it's possible
  3.  *
  4.  * Example chunkArray([1,2,3,4,5,6,7,8,9,10,11], 3)
  5.  * Returns [[1,2,3,4],[5,6,7,8],[9,10,11]]
  6.  */
  7. function chunkArray(array, size) {
  8.     if (size < 2) return array
  9.  
  10.     let len = array.length
  11.     let chunks = []
  12.     let i = 0
  13.     let n
  14.  
  15.     if (len % size === 0) {
  16.         n = Math.floor(len / size)
  17.         while (i < len) {
  18.             chunks.push(array.slice(i, i += n))
  19.         }
  20.     } else {
  21.         while (i < len) {
  22.             n = Math.ceil((len - i) / size--)
  23.             chunks.push(array.slice(i, i += n))
  24.         }
  25.     }
  26.  
  27.     return chunks
  28. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement