简体   繁体   中英

How to return a multidimensional array of numbers in descending order?

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

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.

  1. Join the values using .map() and .join(''))
  2. Use .sort() and .reverse() to order by descending value
  3. Use .split() to break them into single digits again.

 const input = [[1,2,3],[1,3,2],[3,2,1],[3,1,2],[2,1,3],[2,3,1]]; const joined = input.map(arr => arr.join('')); const sorted = joined.sort().reverse(); const result = sorted.map(val => val.split('')); console.log(result);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM