JSFiddle - React, Tailwind, and code Playground
JavaScript
const paginateUs = [
{ item: 'wow' },
{ item: 'I' },
{ item: 'will' },
{ item: 'be' },
{ item: 'paginated' },
{ item: 'soon' },
{ item: 'wow' },
];
// Don't modify the original array, thats generally a bad idea. If a function
// is passed an array as a parameter, it probably shouldn't remove things from it.
// A developer using your function will expect paginated result back, but probably
// won't expect your function to destroy their array, just just leave it alone.
// If for some reason you actually need to remove all items from the original array
// do that separately
function paginate(toPaginate, pageSize) {
const pages = [];
let currentPage = 0;
// Don't mess around with nested loops or nested array constructors and array
// froms. Just a basic forEach is all you need, just keep track of what page you are on.
toPaginate.forEach(item => {
// If the current page isn't an array, make it one
if (!pages[currentPage]) {
pages[currentPage] = [];
}
// Add the item to the current page
pages[currentPage].push(item);
// If our current page's length is at the page size, go to the next page
if (pages[currentPage].length === pageSize) {
currentPage++;
}
});
return pages;
}
// Run code and log array and length to console
const paginated = paginate(paginateUs, 3);
console.log(paginated);
console.log(paginated.length);