使用其索引之一对数组进行排序 [英] sorting array of arrays using one of their indexes
问题描述
我有一个带有不同值的数组,我想按其中一个索引中的数值对它进行排序
I have an array with different values in it and I'd like to sort it by the numeric value in one of the indexes
const arr = [
['foo', var, 5],
['fee', var, 7],
['faa', var, 3]
]
我想使用 arr将此数组从大到小排序[2]
值。知道怎么做吗?
I want to sort this array from big to small using arr[2]
value. Any idea how it can be done?
期望结果应该是:
const arr = [
['fee', var, 7],
['foo', var, 5],
['faa', var, 3]
]
推荐答案
您可以使用排序像这样:
arr.sort((a,b) => {
return a[2] < b[2] // To sort in descending order
// return a[2] > b[2] // To sort in ascending order
})
示例:
var arr = [
['foo', 'fifth', 5],
['fee', 'seventh', 7],
['faa', 'third', 3]
];
var sortedArr = arr.sort(function(a,b){
return a[2] < b[2]
});
console.log(sortedArr)
首先,让我们假设这个数组:
First, let's assume this array:
[1,2] // where a = 1, b = 2
升序:
大于b吗?
如果大于是的,我们需要排序=>返回true
If it is yes, we need to sort => return true
否则,我们不需要排序=>返回false
Else, we don't need to sort => return false
降序:
是否小于b?
如果是,我们需要排序=>返回true
If it is yes, we need to sort => return true
否则,我们不需要排序=>返回false
Else, we don't need to sort => return false
在前面的示例中,我们正在验证a是否小于b,然后返回true对其进行排序
In preceding example, we're verifying if a is lesser than b, then return true to sort it out else return false as this is already in descending order.
按照@ Nina Scholz
请不要返回布尔值进行排序,因为sort需要一个值小于零,零或大于零。忽略相等的情况可能确实有效,但是算法使数组难以排序。
您应该考虑返回0、1或-1。对于您的情况,您应该这样使用:
You should consider returning 0, 1, or -1. For your case, you should use like this:
arr.sort((a,b) => {
if(a[2] < b[2]) return 1
if(a[2] > b[2]) return -1
if(a[2] === b[2]) return 0
})
此外
如果值只是整数(不包含Infinity和NaN),则可以将其简化如下,
If the values are only integers (doesn't contain Infinity and NaN), then it can be simplifies as below,
arr.sort((a,b) => b[2]-a[2])
这篇关于使用其索引之一对数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!