Skip to content

Instantly share code, notes, and snippets.

@AlexcastroDev
Created June 6, 2021 22:41
Show Gist options
  • Save AlexcastroDev/07f125ca77fe1216b3fb1a71213d055e to your computer and use it in GitHub Desktop.
Save AlexcastroDev/07f125ca77fe1216b3fb1a71213d055e to your computer and use it in GitHub Desktop.
how to paginate itens in Javascript
const paginate = (items, page = 1, perPage = 10) => {
const offset = perPage * (page - 1);
const totalPages = Math.ceil(items.length / perPage);
const paginatedItems = items.slice(offset, perPage * page);
return {
previousPage: page - 1 ? page - 1 : null,
nextPage: (totalPages > page) ? page + 1 : null,
total: items.length,
totalPages: totalPages,
items: paginatedItems
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment