按降序排序多维数组

时间:2021-01-05 21:31:56

I have an array that is currently sorted by the first value:

我有一个数组,当前按第一个值排序:

[ [ 'a', 3 ],
  [ 'c', 3 ],
  [ 'd', 1 ],
  [ 'e', 2 ],
  [ 'f', 1 ],
  [ 'g', 1 ],
  [ 'i', 7 ],
  [ 'l', 3 ],
  [ 'o', 2 ],
  [ 'p', 2 ],
  [ 'r', 2 ],
  [ 's', 3 ],
  [ 't', 1 ],
  [ 'u', 2 ],
  [ 'x', 1 ] ]

I would like to sort the digits in descending order to get:

我想按降序排序数字得到:

[ [ 'i', 7 ],
  [ 'a', 3 ],
  [ 'c', 3 ],
  [ 'l', 3 ],
  [ 's', 3 ],
  [ 'e', 2 ],
  [ 'o', 2 ] ......]

3 个解决方案

#1


1  

Use Array.sort([compareFunction])

function comparator(a, b) {    
  if (a[1] > b[1]) return -1
  if (a[1] < b[1]) return 1
  return 0
}

myArray = myArray.sort(comparator)

edit for comment:

编辑评论:

Here is a jslint showing it in action: https://jsfiddle.net/49ed0Lj4/1/

这是一个jslint显示它在行动:https://jsfiddle.net/49ed0Lj4/1/

#2


0  

The sort method in Array

数组中的排序方法

var arr = [
    ['a', 3],
    ['c', 3],
    ['d', 1],
    ['e', 2],
    ['f', 1],
    ['g', 1],
    ['i', 7],
    ['l', 3],
    ['o', 2],
    ['p', 2],
    ['r', 2],
    ['s', 3],
    ['t', 1],
    ['u', 2],
    ['x', 1]
];

arr.sort(function(a, b) {
    return b[1] - a[1]
})

Maybe you need to sort by both the English letters and number. You can change the callback function to do this.

也许你需要按英文字母和数字排序。您可以更改回调函数来执行此操作。

#3


-1  

First, you're going to want to take a look at Array.prototype.sort()

首先,您将要查看Array.prototype.sort()

You'll need to write a comparison function that compares the second value of each array element, and then compares the first if the second values are equal. The examples in the documentation should be a good starting point.

您需要编写一个比较函数来比较每个数组元素的第二个值,然后比较第一个值,如果第二个值相等。文档中的示例应该是一个很好的起点。

#1


1  

Use Array.sort([compareFunction])

function comparator(a, b) {    
  if (a[1] > b[1]) return -1
  if (a[1] < b[1]) return 1
  return 0
}

myArray = myArray.sort(comparator)

edit for comment:

编辑评论:

Here is a jslint showing it in action: https://jsfiddle.net/49ed0Lj4/1/

这是一个jslint显示它在行动:https://jsfiddle.net/49ed0Lj4/1/

#2


0  

The sort method in Array

数组中的排序方法

var arr = [
    ['a', 3],
    ['c', 3],
    ['d', 1],
    ['e', 2],
    ['f', 1],
    ['g', 1],
    ['i', 7],
    ['l', 3],
    ['o', 2],
    ['p', 2],
    ['r', 2],
    ['s', 3],
    ['t', 1],
    ['u', 2],
    ['x', 1]
];

arr.sort(function(a, b) {
    return b[1] - a[1]
})

Maybe you need to sort by both the English letters and number. You can change the callback function to do this.

也许你需要按英文字母和数字排序。您可以更改回调函数来执行此操作。

#3


-1  

First, you're going to want to take a look at Array.prototype.sort()

首先,您将要查看Array.prototype.sort()

You'll need to write a comparison function that compares the second value of each array element, and then compares the first if the second values are equal. The examples in the documentation should be a good starting point.

您需要编写一个比较函数来比较每个数组元素的第二个值,然后比较第一个值,如果第二个值相等。文档中的示例应该是一个很好的起点。