Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

153
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda