Reputation: 33
I am new to JS and I am tring to sort a multidimensional array and I want to return the array in descending order -
Input -
let input = [[1,2,3],[1,3,2],[3,2,1],[3,1,2],[2,1,3],[2,3,1]]
Expected Ouput
[[3,2,1],[3,1,2],[2,3,1],[2,1,3],[1,3,2],[1,2,3]]
I have tried sort
let result = input.sort((a, b) => a - b)
But I am getting the same array sent back to me
[[1,2,3],[1,3,2],[3,2,1],[3,1,2],[2,1,3],[2,3,1]]
I have also tried a for loop with the sort method
for(let i = 0; i < input.length; i++){
let inputArr = input[i]
let output = inputArr.sort((a,b) => a - b)
console.log(output)
}
But I get returned
[1,2,3] 6 times (the length of the original array?)
How do I return the array values in descending order?
Thanks
Upvotes: 0
Views: 69
Reputation: 24638
The sort operation expects numbers. You can apply the .sort()
array method on input
using concatenated inner array elements converted into a number - +arr.join('')
- as in the following demo:
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] ]
NOTE
You may also use parseInt( arr.join('') )
in place of +arr.join('')
.
Upvotes: 0
Reputation: 371019
You need to compare the subarray items against each other - .sort((a, b) -> a - b)
makes no sense because a
and b
are arrays, and so can't be meaningfully subtracted from each other.
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);
That's assuming that the subarrays contain the same number of values, as it is in the example.
Upvotes: 2