How to get the correct items based on number of items, items per page and page number?

I have an array of objects:

let array = [
  { name: 'name1', price: '555' },
  { name: 'nam2', price: '666' }
]

I’m wondering how to get the correct item based on the number of items, items per page and page number? For example, if I have itemsPerPage = 1 and pageNumber = 0, I’d need to return the first object only. If I had itemsPerPage = 1 and pageNumber = 1, I’d need to return the second object and if I had itemsPerPage = 2 and pageNumber = 0, I’d need to return both objects.

I’m having some difficulty figuring out how to use the totalItems, itemsPerPage and pageNumber to determine which object am I meant to return.

Answer

Here’s my code, I also used the array you provided and possible use cases

Everything that needs to be explained was written as a comment in the code

const array = [{
    name: 'name1',
    price: '555'
  },
  {
    name: 'nam2',
    price: '666'
  }
];

function returnRelevantAmount(amountPerPage, pageNumber) {
  if (!amountPerPage) return []; // If amountPerPage is 0
  const start = (pageNumber * amountPerPage); // how many to offset the slice by
  const end = start + amountPerPage; // offset + amountRequired
  
  return array.slice(start, end);
}

console.log(returnRelevantAmount(1, 0));
console.log(returnRelevantAmount(2, 0));
console.log(returnRelevantAmount(1, 1));

A possible one liner would be

const returnRelevantAmount = (amountPerPage, pageNumber) => (!amountPerPage) ? [] : array.slice((pageNumber * amountPerPage), ((pageNumber * amountPerPage) + amountPerPage));

Leave a Reply

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