How to calculate the number of elements on a page and their index using javascript?

I am creating a pagination system for a table and I want to show 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}`);
      

Run codeHide result


now it works well when the number of elements on the page can equally divide the total number of elements, but if it is not, it end

will be incorrect. in the next case if the variable page

is 3 end

will have a value 1

. how can i fix this?

+3


source to share


3 answers


You can use Math.min

.

var end = Math.min(start + numberOfItemsPerPage - 1, totalItemsCount);

      

eg.



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}`);
      

Run codeHide result


+5


source


You can use Math.min

to make sure that the end

total number of items does not exceed.
Here's another solution that looks simpler to 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));
      

Run codeHide result


As you can see, you don't need to Math.floor

, you can use integer division.

+1


source


I suggest using 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));
      

Run codeHide result


+1


source







All Articles