¿Se puede mejorar este código? Primero organiza nuestra matriz en una lista ordenada (array ordenado) y finalArray toma el resultado final; Ejemplo 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);Puede agrupar primero y luego ordenar por el primer elemento de cada matriz.
Si solo tiene valores enteros positivos de 32 bits, puede omitir la ordenación, porque el objeto se ordena como una matriz.
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; }Aquí hay una versión más corta que la tuya y más legible que la de Nina.
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]) => ab); // sort on the first entry console.log(finalArray);