Categories
JavaScript Answers

How to paginate a JavaScript array?

Spread the love

Sometimes, we want to paginate a JavaScript array.

In this article, we’ll look at how to paginate a JavaScript array.

How to paginate a JavaScript array?

To paginate a JavaScript array, we can use the JavaScript array’s slice method.

For instance, we write:

const paginate = (array, pageSize, pageNumber) => {
  return array.slice((pageNumber - 1) * pageSize, pageNumber * pageSize);
}

console.log(paginate([1, 2, 3, 4, 5, 6], 2, 2));
console.log(paginate([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], 4, 1));

to create the paginate function that takes the array we want to pagination and the pageSize and pageNumber.

In the function, we call array.slice to return the elements that should be in the given pageNumber given the pageSize.

We pass in (pageNumber - 1) * pageSize as the start index and pageNumber * pageSize as the end index.

Therefore, from the console log, we get [3, 4] and [1, 2, 3, 4] respectively.

Conclusion

To paginate a JavaScript array, we can use the JavaScript array’s slice method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *