Pagination is a common requirement in web applications especially when dealing with large datasets. It involves dividing a dataset into smaller manageable chunks or pages. In JavaScript, we can paginate an array by splitting it into smaller arrays each representing a page of the data.
Below are the approaches to paginate an Array in JavaScript:
Using array.slice()- This approach uses the array.slice() method to divide the array into smaller chunks.
- It takes two parameters: start and end indicating the start and end indices of the slice.
- By calculating the appropriate start and end indices based on desired page size and current page number we can extract the data for the current page.
Example: Below is an code example of paginating an array in JavaScript using array.slice() method.
JavaScript
function GFG(array, currentPage, pageSize) {
const startIndex = (currentPage - 1) * pageSize;
const endIndex = startIndex + pageSize;
return array.slice(startIndex, endIndex);
}
const data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const currentPage = 2;
const pageSize = 3;
const currentPageData = GFG(data, currentPage, pageSize);
console.log(currentPageData);
Output:
[ 4, 5, 6 ] Using array.splice()- This approach utilizes the array.splice() method to the extract elements from the array.
- Similar to the first approach we calculate the start and end indices based on current page and page size.
- Instead of the returning a new array like slice(), splice() modifies the original array in the place. Therefore, we need to the make a copy of the array before paginating to the avoid altering the original data.
Example: Below is an code example of paginating an array in JavaScript using array.splice() method.
JavaScript
function GFG(array, currentPage, pageSize) {
const startIndex = (currentPage - 1) * pageSize;
const endIndex = startIndex + pageSize;
return array.splice(startIndex, pageSize);
}
const data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const currentPage = 3;
const pageSize = 4;
const currentPageData = GFG(data, currentPage, pageSize);
console.log(currentPageData);
Output:
[ 9, 10 ]
|