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
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.
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('') .