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.
To paginate a JavaScript array, we can use the JavaScript array's slice method. For instance, we write: const paginate = (array, pageSize, pageNumber) => { return array. slice((pageNumber - 1) * pageSize, pageNumber * pageSize); } console.
Method: Array#paginatePaginates a static array (extracting a subset of it). The result is a WillPaginate::Collection instance, which is an array with a few more properties about its paginated state. Parameters: :page - current page, defaults to 1.
JavaScript Pagination concept is applied for moving among the pages with First, Next, Previous and Last buttons or links. Pagination's main motto is to move among the content immediately by clicking links or buttons. Pagination has multiple links or buttons provided for access First, Next, Previous and Last content.
JavaScript Array slice()The slice() method returns selected elements in an array, as a new array. The slice() method selects from a given start, up to a (not inclusive) given end. The slice() method does not change the original array.
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));
Here's a solution with reduce()
:
function paginate (arr, size) { return arr.reduce((acc, val, i) => { let idx = Math.floor(i / size) let page = acc[idx] || (acc[idx] = []) page.push(val) return acc }, []) } let array = [1, 2, 3, 4, 5] let page_size = 2 let pages = paginate(array, page_size) console.log(pages) // all pages console.log(pages[1]) // second page
It returns an array of pages so you can get a certain page, or loop through all of them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With