Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

154
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda