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

283
Vistas
Javascript Array - Create Map with items within a tolerance

Take the following Javascript Array:

["21587569", "21587570", "21587572", "31856855", "31856854"]

You can visually see that the first 3 items are within a limit of 5 of any other item in that "group", the same can be said for the items at index 3 & 4.

How can I group these "similar" items using Javascript array functions, such as the following output array?

[{"21587569", "21587570", "21587572"},{"31856855", "31856854"}]

The items may not always be presented in order as they are in the example input array.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You could sort and get groups if the delta of last items is smaller than five.

const
    data = [21587569, 21587570, 21587572, 31856855, 31856854],
    result = [...data]
        .sort((a, b) => a - b)
        .reduce((r, v) => {
            const last = r[r.length - 1];
            if (!last || v - last[last.length - 1] > 5) r.push([v]);
            else last.push(v);
            return r;
        }, []);

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