Sometimes, we want to paginate a JavaScript array.
In this article, we’ll look at how to paginate a JavaScript array.
Paginate a JavaScript Array
To paginate a JavaScript array, we can use the slice
method to return the chunk of the array we want.
For instance, we can write:
const arr = Array(100).fill().map((_, i) => i)
const paginate = (array, pageSize, pageNumber) => {
return array.slice((pageNumber - 1) * pageSize, pageNumber * pageSize);
}
console.log(paginate(arr, 10, 1))
console.log(paginate(arr, 10, 2))
console.log(paginate(arr, 10, 3))
We have the arr
array with 100 entries.
Then we create paginate
function that takes the array
, pageSize
and pageNumber
parameters.
pageNumber
starts from 1, so we call slice
with (pageNumber — 1) * pageSize
as the first argument and pageNumber * pageSize
as the 2nd argument to return the slice according to a human-readable page number.
Then from the console log, we see:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
[20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
as the returned values of paginate
with pageSize
10 and pageNumber
1, 2, and 3 respectively.
Conclusion
To paginate a JavaScript array, we can use the slice
method to return the chunk of the array we want.