Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

143
Views
¿Cómo puedo mejorar este código Javascript que organiza la matriz en una lista ordenada primero y los coloca en una matriz de matriz con el mismo valor?

¿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);

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!