Search code examples
javascriptarrayspagination

Paginate Javascript array


I am trying to write a Javascript function that takes an array, page_size and page_number as parameters and returns an array that mimics paginated results:

paginate: function (array, page_size, page_number) {
  return result;
}

so for example when:

array = [1, 2, 3, 4, 5],
page size = 2,
page_number = 2,

the function should return: [3, 4].

Any ideas would be appreciated.


Solution

  • You can use Array.prototype.slice and just supply the params for (start, end).

    function paginate(array, page_size, page_number) {
      // human-readable page numbers usually start with 1, so we reduce 1 in the first argument
      return array.slice((page_number - 1) * page_size, page_number * page_size);
    }
    
    console.log(paginate([1, 2, 3, 4, 5, 6], 2, 2));
    console.log(paginate([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], 4, 1));