Paginate Javascript array

前端 未结 7 1867
庸人自扰
庸人自扰 2020-12-02 08:55

I am trying to write a Javascript function that takes an array, page_size and page_number as parameters and returns an array that mimi

7条回答
  •  盖世英雄少女心
    2020-12-02 09:42

    You can use Array.filter() with the help of its second parameter (the index of the current element being processed in the array).

    You'll also need the currently selected page and the number of items per page to display, so you can find the minimum and maximum index of the elements needed.

    const indexMin = selectedPage * elementsPerPage;
    const indexMax = indexMin + elementsPerPage;
    const paginatedArray = arrayToPaginate.filter(
      (x, index) => index >= indexMin && index < indexMax
    );
    

    Updating the selectedPage and/or the elementsPerPage value will allow to return the correct items to display.

提交回复
热议问题