1

I want to make pagination with format like this: 1, 2, 3, ..., latest three.

This is my code:

let skip = null;
    if(pageCount > 10){
        skip = <li><span>...</span></li>
    }
for(let i = 1; i <= pageCount; i++) {

    if((i < page + 3 && i > page - 3)){
            result.push(
                <li key={i}>some link</li>
            );
            continue;
        } else if(skip){
            result.push(skip);
            skip = null;
        }
}

I have pageCount, which is for the example 20 and page, which is the number of the current page, for the example - 3.

I have tried many things, but still can't figure out how to do that.

The format that, I am trying to do is

if page=10, pageCount=20 :

8, 9, 10, ..., 18, 19, 20.

If page=1:

1, 2, 3, ..., 18, 19, 20.

If page=20:

1, 2, 3, ..., 18, 19, 20.

3 Answers 3

1

you're close to the solution.

Maybe this will help you

function smartPagination(current, last){
    var delta = 2,
    left = current - delta,
    right = current + delta + 1,
    range = [],
    rangeWithDots = [],
    l;

    for (let i = 1; i <= last; i++) if (i == 1 || i == last || i >= left && i < right) range.push(i);

    for (let i of range) {
        if (l) {
            if (i - l === 2) rangeWithDots.push(l + 1);
            else if (i - l !== 1) rangeWithDots.push('...');
        }
        rangeWithDots.push(i);
        l = i;
    }

    return rangeWithDots;
}
//Outputs: [1, 2, 3, "...", 9, 10]
Sign up to request clarification or add additional context in comments.

Comments

1

My solution is like as:

function p(page, pageCount = 20){
    pagination = []

    if(page - 3 < 0 || page > pageCount - 3)
        pagination = [1,2,3, '...',pageCount-2, pageCount-1, pageCount-0]

    else {
        for(let i = page-2; i <= page; i++) {
            pagination.push(i)
        }
        pagination.push('...',pageCount-2, pageCount-1, pageCount-0)
    }

    return pagination
}



console.log('page = 10 => ', p(10))
console.log('page = 1 => ', p(1))
console.log('page = 20 => ', p(20))

The results are:

  • page = 10 => (7) [8, 9, 10, "...", 18, 19, 20]
  • page = 1 => (7) [1, 2, 3, "...", 18, 19, 20]
  • page = 20 => (7) [1, 2, 3, "...", 18, 19, 20]

Comments

1
function getRange(page, pageCount, offset) {
  let results = [...Array(pageCount + 1).keys()];
  const skip = '...';

  results = results.slice(page, pageCount + 1);
  results.splice(offset, 0, skip);
  results.splice(offset + 1, results.length - (offset + 1) - offset);

  return results;
}

Outputs:
console.log(getRange(1, 20)); //[ 1, 2, 3, "...", 18, 19, 20 ] console.log(getRange(10, 20)); //[ 10, 11, 12, "...", 18, 19, 20 ]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.