简体   繁体   English

如何按降序返回多维数组?

[英]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 -我是 JS 的新手,我正在尝试对多维数组进行排序,我想按降序返回数组 -

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我也尝试过使用 sort 方法的 for 循环

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.您需要将子数组项相互比较 - .sort((a, b) -> a - b)没有意义,因为ab是 arrays,因此不能有意义地相互减去。

 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(''))使用.map().join(''))连接值
  2. Use .sort() and .reverse() to order by descending value使用.sort().reverse()按降序排序
  3. Use .split() to break them into single digits again.使用.split()再次将它们分解为个位数。

 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:您可以使用转换为数字的串联内部数组元素对input应用.sort()数组方法 - +arr.join('') - 如以下演示所示:

 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('') .您也可以使用parseInt( arr.join('') )代替+arr.join('')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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