Search code examples
javascriptarrayssplitdivide

How to divide an array to chunks with flexible output length?


How to divide an array to chunks with flexible output length?
it's necessary for render pagination, where we have limited place for elements,
and if we have several pages of elements — we need to display buttons with arrays (prev/next) instead el's.

example f() input-output, when 1st argument is Array with data,
and 2nd arg is maximum of elements in list, including nav-buttons:

      f([1,2,3,4], 4) => [1,2,3,4]
    f([1,2,3,4,5], 4) => [[1,2,3], [4,5]]
  f([1,2,3,4,5,6], 4) => [[1,2,3], [4,5,6]]
f([1,2,3,4,5,6,7], 4) => [[1,2,3], [4,5], [6,7]]
f([7,6,5,4,3,2,1], 4) => [[7,6,5], [4,3], [2,1]]
f([1,2,3,4,5,6,7], 6) => [[1,2,3,4,5], [6,7]]


Example of design-layout with max 6 elements

1st page:
1st page

2nd page:
2nd page

Last page:
Last page


Solution

  • First, determine if one page/two pages are enough. If not, loop the array.

    let f = (array, max) => {
      if (array.length / max <= 1)
        return array
    
      if (array.length / (max - 1) <= 2)
        return [array.slice(0, max - 1), array.slice(max - 1, array.length)]
    
      let result = []
      let n = 0
      while (n <= array.length - 1) {
        if (n == 0) {
          result.push(array.slice(n, n + max - 1))
          n += max - 1
        } else {
          let pushAmount = n+max-1 >= array.length ? max-1 : max-2
          result.push(array.slice(n, n + pushAmount))
          n += pushAmount
        }
      }
    
      return result
    }
    
    console.log(f([1, 2, 3, 4], 4))
    console.log(f([1, 2, 3, 4, 5], 4))
    console.log(f([1, 2, 3, 4, 5, 6], 4))
    console.log(f([1, 2, 3, 4, 5, 6, 7], 4))
    console.log(f([7, 6, 5, 4, 3, 2, 1], 4))
    console.log(f([1, 2, 3, 4, 5, 6, 7], 6))