How to split an array into pages
Short answer
Page page starts at (page - 1) * perPage. slice() takes the needed part:
const items = Array.from({ length: 23 }, (_, i) => i + 1);
const perPage = 10;
const page = 3;
const pageItems = items.slice((page - 1) * perPage, page * perPage);
console.log(pageItems.join(', '));Output:
21, 22, 23The number of pages
Round the division up so the last incomplete page is counted:
const total = 23;
const perPage = 10;
console.log(Math.ceil(total / perPage));Output:
3A helper function
Return the items together with the information about pages:
const paginate = (items, page, perPage) => ({
items: items.slice((page - 1) * perPage, page * perPage),
page,
pages: Math.ceil(items.length / perPage),
});
const result = paginate(['a', 'b', 'c', 'd', 'e'], 2, 2);
console.log(result.items.join(', '), `page ${result.page} of ${result.pages}`);Output:
c, d page 2 of 3Common mistake
Page numbers on the site usually start at 1, but array indexes start at 0. Without - 1, the first page is skipped:
const items = ['a', 'b', 'c', 'd'];
console.log(items.slice(1 * 2, 2 * 2).join(', '));Output:
c, dFunctions used in this recipe
- Array.prototype.slice — Returns part of an array.
- Math.ceil — Rounds a number up to an integer.