Javascript:对多维数组进行排序
我有一个多维数组,有 3 列(通过使用 javascript)
[0] Number of vote
[1] Name of candidate
[2] Candidate Number
我的数组内容是:
1 | Peter | 3
1 | Mary | 2
0 | David | 5
0 | John | 4
0 | Billy | 1
如何按 [0] 投票数 然后 [2] 候选人数< 对数组进行排序/em>?
结果应该是:
1 | Mary | 2
1 | Peter | 3
0 | Billy | 1
0 | John | 4
0 | David | 5
I have a Multidimensional Array which has 3 columns (by using javascript)
[0] Number of vote
[1] Name of candidate
[2] Candidate Number
My array contents are:
1 | Peter | 3
1 | Mary | 2
0 | David | 5
0 | John | 4
0 | Billy | 1
How can I sort the array by [0] Number of vote and then [2] candidate number?
The result should be:
1 | Mary | 2
1 | Peter | 3
0 | Billy | 1
0 | John | 4
0 | David | 5
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如前所述,您应该使用自定义排序函数。这是一个完全可以满足您的要求的产品。
As previously said, you should use a custom sort function. Here's one that would do exactly what you want.
这是一个通用函数
Here is a generic function
要对多维数组进行排序,首先按坐标 0 进行比较,然后按分量 2 进行比较,您可以将两个比较函数与
||
结合起来:对于数值,只需使用差异作为比较函数,如
x - y
为:x == 如果
x > y
x
y
调整差异中元素的顺序以处理升序/降序。
To sort a multi-dimensional array comparing by coordinate 0 first and then by component 2 you can combine two compare functions with
||
:For numeric values simply use a difference as a compare function, as
x - y
is:x == y
x > y
x < y
Adjust the order of the elements in the differences to take care of ascending/descending order.
据我所知,您必须创建自己的排序功能。
如果您可以将其存储在一个对象中,那么像前面的答案中那样定义一个函数就可以完成这项工作。
请参阅对对象数组进行排序
As far as I know you will have to make your own sorting function.
If you can store it in a object than defining a function like in the previous answer will do the job.
Refer Sort array of objects
另一种方法是为每个数组条目创建一个值,例如 1000*投票数 + 候选人数,以便该值明确且唯一,例如我们得到 1003, 1002, 5, 4, 1。添加一个引用回的键原始数组并排序。
因此,我们将按每个子数组的第一个元素对 [[1003,0],[1002,1],[5,2],[4,3],[1,4]] 进行排序。
您的排序系统存在差异,您对选票使用高->低,对候选人编号使用低-高。
Another method is to create a value for each array entry, e.g. 1000*number of votes + candidate number, so that this value is unambiguous and unique, e.g. we get 1003, 1002, 5, 4, 1. Add a key refering back to the original array and sort.
So we would sort [[1003,0],[1002,1],[5,2],[4,3],[1,4]] by the first element of each subarray.
There is a discrepancy in your sorting system, you use high->low for votes and low-high for candidate number.