How to Paginate an Array in JavaScript?

You may want to establish pagination using an array of objects depending on your needs. This tutorial will show you how to paginate an array object in Javascript. You may accomplish this in a variety of methods, including using slice, filter, and reduce.

In JavaScript, I want to be able to take an array of URLs and paginate to the proper one by clicking the previous and next buttons.

Here is the HTML code:

<button id="behind"></button> 
<button id="forward"></button>

And the JavaScript, which was adapt from a StackOverflow answer. Where users want another method here is the problem of the user.

I have an array of strings, and clicking the “NEXT” button causes the next array item to be displayed in a p> tag while clicking the “PREV” button causes the prior one to be displayed. It continues from the first (last) item when it reaches the end (beginning)
This is what I might have come up with after struggling to find a way to retrieve the correct item index when PREV is clicked.
On reducing array indices, I used the modulo operator. I’m curious whether there is a better method to accomplish this. By the way, I prefer ES6 syntax, so any ES5 compatibility enhancements are irrelevant to me.

Here is an alternative way:

var host = 'https://' + document.location.hostname
var pages = [host + '/index.html', host + '/index2.html', host + '/index3.html']

var behind = document.getElementById('behind')
var forward = document.getElementById('forward')

function prev(current, pages) {
  var index = pages.indexOf(current)
  if (index === 0) {
    return pages[pages.length - 1]
  }
  return pages[index - 1]
}

function next(current, pages) {
  var index = pages.indexOf(current)
  if (index === pages.length - 1) {
    return pages[0]
  }
  return pages[index + 1]
}

behind.addEventListener('click', function () {
  var newUrl = prev(host + window.location.pathname, pages)
  window.location.href = newUrl
})

forward.addEventListener('click', function () {
  var newUrl = next(host + window.location.pathname, pages)
  window.location.href = newUrl
})

If you want something a bit more detailed, though, you may be a little more verbose and come up with something that, while not as concise, provides you with more information.

In my case, I was looking for the next and previous pages, as well as the total number of pages and items for each paginated page. It gets a lot more handier when the method becomes more verbose.

That’s all for this article if you have any queries please contact us through our website or email us at [email protected]

Leave a Comment