I am building a pagination system for a table and want to show a text like 1 to 5 of 14 entries
i have the following code
var totalItemsCount = 14;
var numberOfItemsPerPage = 5;
var page = 1;
var numberOfPages = Math.floor((totalItemsCount + numberOfItemsPerPage - 1) / numberOfItemsPerPage);
var start = (page * numberOfItemsPerPage) - (numberOfItemsPerPage - 1);
var end = start + numberOfItemsPerPage - 1;
console.log(`${start} to ${end} of ${totalItemsCount}`);
I am building a pagination system for a table and want to show a text like 1 to 5 of 14 entries
i have the following code
var totalItemsCount = 14;
var numberOfItemsPerPage = 5;
var page = 1;
var numberOfPages = Math.floor((totalItemsCount + numberOfItemsPerPage - 1) / numberOfItemsPerPage);
var start = (page * numberOfItemsPerPage) - (numberOfItemsPerPage - 1);
var end = start + numberOfItemsPerPage - 1;
console.log(`${start} to ${end} of ${totalItemsCount}`);
now this works well when the number of items per page can equally divide the total number of items but when that is not the case end
will be incorrect. in the following case if the variable page
is 3 end
will be of by 1
. how can i fix this?
3 Answers
Reset to default 15You could use Math.min
.
var end = Math.min(start + numberOfItemsPerPage - 1, totalItemsCount);
e.g.
var totalItemsCount = 14;
var numberOfItemsPerPage = 5;
var page = 3;
var numberOfPages = Math.floor((totalItemsCount + numberOfItemsPerPage - 1) / numberOfItemsPerPage);
var start = (page * numberOfItemsPerPage) - (numberOfItemsPerPage - 1);
var end = Math.min(start + numberOfItemsPerPage - 1, totalItemsCount);
console.log(`${start} to ${end} of ${totalItemsCount}`);
You can use Math.min
to make sure that end
does not exceed the total number of items.
Here is another solution which looks simpler for me:
function getPaginationText(totalItemsCount, numberOfItemsPerPage, page) {
var pagesCount = (totalItemsCount - 1) / numberOfItemsPerPage + 1;
var start = (page - 1) * numberOfItemsPerPage + 1;
var end = Math.min(start + numberOfItemsPerPage - 1, totalItemsCount);
return `${start} to ${end} of ${totalItemsCount}`;
}
console.log(getPaginationText(14, 5, 1));
console.log(getPaginationText(14, 5, 2));
console.log(getPaginationText(14, 5, 3));
As you can see, you don't need Math.floor
, you can utilize integer division.
I suggest to use a slightly different approach for calculating the parameter.
var pagination = (page, total, itemsOnPage) => {
var numberOfPages = Math.ceil(total / itemsOnPage),
start = (page - 1) * itemsOnPage + 1,
end = Math.min(page * itemsOnPage, total);
return `${start} to ${end} of ${total} on page ${page} of ${numberOfPages}`;
};
console.log(pagination(1, 14, 5));
console.log(pagination(2, 14, 5));
console.log(pagination(3, 14, 5));
console.log(pagination(3, 15, 5));