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

159
Views
¿Cómo ordenar una matriz de objetos por múltiples claves?

Tengo esta matriz:

 let arr = [{ "guid": 1, creationDateTime: 1632180639045, "pricePerUnitPerHour": 5, "awardedSavingCalculationStatus": 1, divisible: true, }, { "guid": 2, creationDateTime: 2504091567119, "pricePerUnitPerHour": 20, "awardedSavingCalculationStatus": 1, divisible: true, }, { "guid": 3, creationDateTime: 1504095567183, "pricePerUnitPerHour": 5, "awardedSavingCalculationStatus": 1, divisible: true, }]

Necesito hacer la clasificación ascendente por estas tres propiedades precio por unidad por hora, divisible y creación fecha y hora.

Entonces, si, por ejemplo, dos objetos tienen valores iguales en precio por unidad por hora, la clasificación debería ser por propiedad divisible. Ahí divisible:true debería estar antes del objeto donde tenemos divisible:false.

Y al final, si tienen dos precios iguales, la propiedad divisible es verdadera, por ejemplo, la clasificación debe realizarse en función de la marca de tiempo: creaciónDateTime

lo que intenté

Encontré algunas respuestas en stackoverflow, pero allí él hace la clasificación por solo dos campos, pero no puedo encontrar una manera de ordenar por el tercero.

 arr.sort( function (a, b) { if (a.pricePerUnitPerHour === b.pricePerUnitPerHour) { return b.divisible - a.divisible; } if(a.divisible === b.divisible) { return new Date(a.creationDateTime) - new Date(b.creationDateTime) } return a.pricePerUnitPerHour > b.pricePerUnitPerHour ? 1 : -1; });

Aquí la clasificación funciona si los precios y los divisibles son los mismos, entonces se clasifican por ellos, pero en la fecha y hora de creación no se clasifican en orden ascendente.

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

0

Ordenar de la siguiente manera:

 arr.sort(function(a, b) { return a.pricePerUnitPerHour - b.pricePerUnitPerHour || -(a.divisible - b.divisible) || a.creationDateTime - b.creationDateTime; });

La operación de resta devolverá 0 si ambos valores son iguales (doh), en cuyo caso el código pasa a la siguiente comparación. El caso verdadero/falso debe invertirse ya que desea que 1 (verdadero) se ordene antes que 0 (falso).

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!