I'm doing pagination in an embed and I wanted to split 4 elements from an array for each page. How do I do this? (to update when I click the button). Until then I have only the first step which is to get the first 4 elements, from the first page, with:
.slice(0, 4)
How do I get the next 4, and the next, and so on...
CodePudding user response:
you need to define:
- currentPage variable (set to 1 as default value)
- pageSize - how many items should be for one page
- countPages - for calculation, rounded in bigger side
I have written 3 methods
loadFirstPage()
loadNextPage()
loadPrevPage()
const input = [1,2,3,4,5,6,7,8,9,10,11,12,13];
let currentPage = 1;
let pageSize = 4;
const countPages = Math.ceil(input.length / pageSize);
function loadFirstPage() {
currentPage = 1;
return [...input].splice(0, pageSize)
}
function loadNextPage() {
const nextPage = currentPage 1;
if (nextPage <= countPages) {
currentPage = nextPage;
const startIndex = currentPage * pageSize - pageSize;
return [...input].splice(startIndex, pageSize)
} else {
currentPage = countPages;
const startIndex = currentPage * pageSize - pageSize;
return [...input].splice(startIndex, pageSize)
}
}
function loadPrevPage() {
const prevPage = currentPage - 1;
if (prevPage >= 1) {
currentPage = prevPage;
const startIndex = currentPage * pageSize - pageSize;
return [...input].splice(startIndex, pageSize)
} else {
currentPage = 1;
const startIndex = currentPage * pageSize - pageSize;
return [...input].splice(startIndex, pageSize)
}
}
console.log('output data: ', loadFirstPage(), 'current page: ', currentPage);
console.log('output data: ', loadNextPage(), 'current page: ', currentPage);
console.log('output data: ', loadNextPage(), 'current page: ', currentPage);
console.log('output data: ', loadNextPage(), 'current page: ', currentPage);
console.log('output data: ', loadNextPage(), 'current page: ', currentPage);
console.log('output data: ', loadPrevPage(), 'current page: ', currentPage);
console.log('output data: ', loadPrevPage(), 'current page: ', currentPage);
console.log('output data: ', loadPrevPage(), 'current page: ', currentPage);
console.log('output data: ', loadPrevPage(), 'current page: ', currentPage);