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

186
Visualizações
How to get three element after an particular index of a array?

I have two array

const array1 = [12, 13, 14, 15, 16, 17, 18, 19, 20]
const array2 = [17, 18]

I want to return first three element from array1 after comparing the index of array2 17 element or first element with the array1.

desired O/P from array1 after comparing is [14, 15, 16]

i have tried getting the index of the particular element.

const indexOf17FromArray1 = array1.indexOf(array2[0]) //5
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

just do array.slice((idx - 3), idx)

about 4 years ago · Juan Pablo Isaza Relatório

0

You can combine the use of array methods indexOf and slice.

First determine the last index (like you already have). Then based on your desired length modify it for use with slice. slice takes the start and end indices.

const array1 = [12, 13, 14, 15, 16, 17, 18, 19, 20];
const array2 = [17, 18];

const length = 3;

const indexOf17FromArray1 = array1.indexOf(array2[0])
console.log(array1.slice(indexOf17FromArray1 - length,  indexOf17FromArray1));

about 4 years ago · Juan Pablo Isaza Relatório

0

You could get the index and check if -1 or subtract an offset and get a new array.

const
    array = [12, 13, 14, 15, 16, 17, 18, 19, 20],
    value = 17,
    index = array.indexOf(value),
    result = index === -1
        ? []
        : array.slice(Math.max(index - 3, 0), index);

console.log(result);

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