Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Display Paginated column index in reverse order

I’m facing a problem during the display of paginated data. Default the program will display 5 rows per page and during the column index it is displaying the row no starting from 1, and then on the second page the row no will start from 6.

idx: 1 | name: John
idx: 2 | name: Doe
idx: 3 | name: John
idx: 4 | name: Doe
idx: 5 | name: John

page = 2:

idx: 6 | name: Tim
idx: 7 | name: John
idx: 8 | name: Doe
idx: 9 | name: John
idx: 10 | name: Doe

Code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const names = [
    "John",
    "Doe",
    "John",
    "Doe",
    "John",
    "Tim",
    "John",
    "Doe",
    "John",
    "Doe",
];

let page = 1;
let limit = 5;
let totalCount = names.length || 0;

function pagination(array, page, limit) {
    return array.slice((page - 1) * limit, page * limit);
}

const newArray = pagination(names, page, limit);

newArray.forEach((item, index) => {
    const idx = (page - 1) * limit + (index + 1);
    console.log("idx:", idx, "|", "name:", item);
});

When I change page no to 2, then it will display starting row no 6 on the second page.

But the problem is I want to display the row indexing in reverse order something like this:
the first row should display the index as 10, and on the second page, the index starts from 5. How can I achieve this and what is the formula for this?

idx: 10 | name: John
idx: 9 | name: Doe
idx: 8 | name: John
idx: 7 | name: Doe
idx: 6 | name: John

page = 2:

idx: 5 | name: Tim
idx: 4 | name: John
idx: 3 | name: Doe
idx: 2 | name: John
idx: 1 | name: Doe

>Solution :

You need to change only on idx varible calculation. hope it’s useful for you.

const names = [
  "John",
  "Doe",
  "John",
  "Doe",
  "John",
  "Tim",
  "John",
  "Doe",
  "John",
  "Doe",
];

let page = 1;
let limit = 5;
let totalCount = names.length || 0;

function pagination(array, page, limit) {
  return array.slice((page - 1) * limit, page * limit);
}

const newArray = pagination(names, page, limit);

newArray.forEach((item, index) => {
  const idx = totalCount - ((page - 1) * limit) - index;
  console.log("idx:", idx, "|", "name:", item);
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading