{}

Set Pagination

Sets a pagination object based on an array.

        
    function setPagination(array, quantity) {
      return array.reduce((accumulator, currentValue, index) => {
        if (!index) accumulator[1] = [];
  
        const keys = Object.keys(accumulator);
        const lastPage = Number(keys[keys.length - 1]);
  
        if (accumulator[lastPage].length < quantity) accumulator[lastPage].push(currentValue);
        else accumulator[lastPage + 1] = [currentValue];
  
        return accumulator;
      }, {});
    }
      

Usage

        
    const data = [
      { name: 'John' },
      { name: 'John' },
      { name: 'John' },
      { name: 'John' },
      { name: 'John' },
      { name: 'John' },
      { name: 'John' },
    ];
  
    setPagination(data, 3);
      

Output

        
    {
      "1": [
        { "name": "John" },
        { "name": "John" },
        { "name": "John" }
      ],
      "2": [
        { "name": "John" },
        { "name": "John" },
        { "name": "John" }
      ],
      "3": [
        { "name": "John" }
      ]
    }