Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

151
Views
Get the 5 items before and after the current index in an array

Say I have an array that looks like this

arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

These array represents page numbers in my scenario. Say if I am on page 8, I'd like to create a seperate array that includes the following The first 5 before page 8 and the first 5 after page 8.

i.e first 11 items array.

[3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

Therefore having 11 items in an array including that page itself.

If the array is smaller than 5, then simply return the rest.

i.e

if the array looks like this [2,3,4,5,6,7,8] and if the page is 4, since the before does not have 5 items exactly I'd like to get all of it.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You can use the slice method of the Array.

function paginatorNumbers(arr, currentIndex) {
    return arr.length > 5 && currentIndex > 5
        ? arr.slice(currentIndex - 6, currentIndex + 5)
        : arr.slice(0, currentIndex + 5)
}
about 4 years ago · Juan Pablo Isaza Report

0

EDITED:

This should work now

const getRange = (array, index) => {

 // You need constraints if index - 5 is < 0
 const startIndex = Math.max(0, index - 5 - 1);

 const endIndex = index+ 5;

 return array.slice(startIndex, endIndex);

} 
about 4 years ago · Juan Pablo Isaza Report

0

You can makeit very simple with Plus and Minus.

arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

function getRange(current) {
  let start = (current -5)
  let end = (current + 5)
  let res = []
  start = start < 0 ? 0 : start
  for(start; start <= end; start++) {
    res.push(start)
  }
  return res;
}

console.log(getRange(8)) // starts from 3
console.log(getRange(2)) // starts from 0

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!