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

138
Vistas
How can i improve this Javascript code that arrange the array in ordered list first and put them in an array of array with same value?

Can this code be Improved? It arrange our array into sorted list(sortedArray) first and, the finalArray takes the final result;Example finalArray = [[1,1,1,1][2,2,2]...]

let array = [1, 2, 4, 591, 392, 391, 2, 5, 10, 2, 1, 1, 1, 20, 20]
let sortedArray = []
let finalArray = []

sortedArray = array.sort((a, b) => {
  if (a > b) return 1;
  if (a < b) return -1;
  return sortedArray.push(a - b);
});

finalArray = sortedArray.reduce((item, index) => {
  if (typeof item.last === 'undefined' || item.last !== index) {
    item.last = index;
    item.sortedArray.push([]);
  }
  item.sortedArray[item.sortedArray.length - 1].push(index);
  return item;

}, {
  sortedArray: []
}).sortedArray;
console.log(finalArray);

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

0

You could group first and then sort by the first item of each array.

If you have only positive 32 bit intger values, you could omit sorting, because the object is sorted like an array.

const
    array = [1, 2, 4, 591, 392, 391, 2, 5, 10, 2, 1, 1, 1, 20, 20],
    result = Object
        .values(array.reduce((r, v) => {
            (r[v] ??= []).push(v);
            return r;
        }, {}))
        .sort(([a], [b]) => a - b);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

about 4 years ago · Juan Pablo Isaza Denunciar

0

Here is a shorter version than yours and more readable than Nina's

let array = [1, 2, 4, 591, 392, 391, 2, 5, 10, 2, 1, 1, 1, 20, 20]

const finalArray = array.slice(0) // copy the array
  .reduce((acc,cur) => {
    const idx = acc.findIndex(item => item[0] === cur);
    if (idx !=-1) acc[idx].push(cur); // just push
    else acc.push([cur]); // push as array
    return acc
  },[])
  .sort(([a],[b]) => a-b); // sort on the first entry

console.log(finalArray);

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