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

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

0

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

about 4 years ago · Juan Pablo Isaza Denunciar

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 Denunciar

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 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