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

150
Views
¿Cómo devolver una matriz multidimensional de números en orden descendente?

Soy nuevo en JS y estoy tratando de ordenar una matriz multidimensional y quiero devolver la matriz en orden descendente:

Aporte -

 let input = [[1,2,3],[1,3,2],[3,2,1],[3,1,2],[2,1,3],[2,3,1]]

Salida esperada

 [[3,2,1],[3,1,2],[2,3,1],[2,1,3],[1,3,2],[1,2,3]]

he intentado ordenar

 let result = input.sort((a, b) => a - b)

Pero me devuelven la misma matriz

 [[1,2,3],[1,3,2],[3,2,1],[3,1,2],[2,1,3],[2,3,1]]

También probé un bucle for con el método de clasificación

 for(let i = 0; i < input.length; i++){ let inputArr = input[i] let output = inputArr.sort((a,b) => a - b) console.log(output) }

pero me devuelven

 [1,2,3] 6 times (the length of the original array?)

¿Cómo devuelvo los valores de la matriz en orden descendente?

Gracias

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

0

Debe comparar los elementos del subarreglo entre sí: .sort((a, b) -> a - b) no tiene sentido porque a y b son matrices, por lo que no se pueden restar significativamente entre sí.

 let input = [[1,2,3],[1,3,2],[3,2,1],[3,1,2],[2,1,3],[2,3,1]]; input.sort((a, b) => { // Find the first index that's different between the two subarrays being compared const diffIndex = a.findIndex((itemA, i) => b[i] !== itemA); // Return the difference, so that the higher value will come first in the result // If no difference found, return 0 (so they will come next to each other) return diffIndex === -1 ? 0 : b[diffIndex] - a[diffIndex]; }); console.log(input);

Eso suponiendo que los subarreglos contienen la misma cantidad de valores, como en el ejemplo.

about 4 years ago · Juan Pablo Isaza Report

0

La operación de clasificación espera números. Puede aplicar el método de matriz .sort() en input usando elementos de matriz internos concatenados convertidos en un número - +arr.join('') - como en la siguiente demostración:

 let input = [ [1,2,3], [1,3,2], [3,2,1], [3,1,2], [2,1,3], [2,3,1] ]; const sorted = input.sort( (a,b) => +b.join('') - +a.join('') ); console.log( sorted ); //OUTPUT: [ [3,2,1], [3,1,2], [2,3,1], [2,1,3], [1,3,2], [1,2,3] ]

NOTA

También puede usar parseInt( arr.join('') ) en lugar de +arr.join('') .

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!