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

180
Vistas
All elements after first occurrence of closest element or first nearest by element

How would you write a function in JS for the following: Get the subarray of all elements:

  • after and including the first occurrence of the searched element
  • or after and including the first number greater than the searched element.

These tests should pass:

expect(elementsStartingFrom([1, 3, 5, 7, 9, 11], 1)).toEqual([1, 3, 5, 7, 9, 11]);
expect(elementsStartingFrom([1, 3, 5, 7, 9, 11], 2)).toEqual([3, 5, 7, 9, 11]);
expect(elementsStartingFrom([1, 3, 5, 7, 9, 11], 3)).toEqual([3, 5, 7, 9, 11]);
expect(elementsStartingFrom([1, 3, 5, 1, 4, 5], 2)).toEqual([3, 5, 1, 4, 5]);
about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

First, use indexOf to see if the item is in the list. If not, filter out anything less than, sort that to get next biggest, then use indexOf to find the index of that. Finally, use slice to get the part of the array:

const elementsStartingFrom = (haystack, needle) => {
    let idx = haystack.indexOf(needle);
    if (-1 == idx) {
        const tmp = haystack.filter(i => i > needle).sort((a, b) => a - b).at(0);
        idx = haystack.indexOf(tmp);
    }
    if (idx == -1) return null;
    else return haystack.slice(idx);
};

You could remove the first call to indexOf and get the same result by changing the < to <=:

const elementsStartingFrom = (haystack, needle) => {
    const tmp = haystack.filter(i => i >= needle).sort((a, b) => a - b).at(0);
    const idx = haystack.indexOf(tmp);
    return (idx == -1) ? null : haystack.slice(idx);
};
about 4 years ago · Santiago Trujillo 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