Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Paginate Javascript array

I am trying to write a Javascript function that takes an array, page_size and page_number as parameters and returns an array that mimics paginated results:

paginate: function (array, page_size, page_number) {   return result; } 

so for example when:

array = [1, 2, 3, 4, 5], page size = 2, page_number = 2, 

the function should return: [3, 4].

Any ideas would be appreciated.

like image 250
SalmaFG Avatar asked Mar 13 '17 10:03

SalmaFG


People also ask

How can I paginate an array of objects in JavaScript?

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.

Can you Paginate an array?

Method: Array#paginatePaginates a static array (extracting a subset of it). The result is a WillPaginate::Collection instance, which is an array with a few more properties about its paginated state. Parameters: :page - current page, defaults to 1.

How can I use pagination in JavaScript?

JavaScript Pagination concept is applied for moving among the pages with First, Next, Previous and Last buttons or links. Pagination's main motto is to move among the content immediately by clicking links or buttons. Pagination has multiple links or buttons provided for access First, Next, Previous and Last content.

How do you slice an array in JavaScript?

JavaScript Array slice()The slice() method returns selected elements in an array, as a new array. The slice() method selects from a given start, up to a (not inclusive) given end. The slice() method does not change the original array.


2 Answers

You can use Array.prototype.slice and just supply the params for (start, end).

function paginate(array, page_size, page_number) {    // human-readable page numbers usually start with 1, so we reduce 1 in the first argument    return array.slice((page_number - 1) * page_size, page_number * page_size);  }    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));
like image 183
casraf Avatar answered Sep 23 '22 17:09

casraf


Here's a solution with reduce():

function paginate (arr, size) {    return arr.reduce((acc, val, i) => {      let idx = Math.floor(i / size)      let page = acc[idx] || (acc[idx] = [])      page.push(val)        return acc    }, [])  }    let array = [1, 2, 3, 4, 5]  let page_size = 2  let pages = paginate(array, page_size)    console.log(pages)    // all pages  console.log(pages[1]) // second page

It returns an array of pages so you can get a certain page, or loop through all of them.

like image 29
dodov Avatar answered Sep 22 '22 17:09

dodov