I recently released a project called ReqRes, which allows you to test your front-end interfaces and AJAX requests against a hosted JSON REST-API.
You can check out the full source of the application on GitHub if you’d like.
All the data that the API sent to the user was stored in a JSON file, not a database, so querying and sorting the data meant that I couldn’t use standard database operations, but standard (with Lo-Dash’s help) array methods to achieve what I needed; pagination.
If you’ve not met Lo-Dash before, it’s “A utility library delivering consistency, customization, performance, & extras”. It’s marketed as a more performant Underscore.js, so if you’re used to using that, maybe give Lo-Dash a try.
So I had an array which I needed to paginate, like so:
I then needed to accept a page parameter (ie. the range of data the developer wanted). So my final function ended up looking something like this (which I’ll break down):
So now, all we need to do is to pass in our array of data and a page number, and we’ll receive in return a fully populate pagination object.
Enter your email address below to keep up to date with new posts & news related to the site