我有很多这样的用户点:
let groupRank = [];
userA = ["Sara", "24"];
userB = ["John", "12"];
userC = ["Eddi", "20"];
userD = ["Marry", "13"];
我想根据他们的观点对他们进行排名并得到:
Console.log(groupRank);
//Sara, Eddi, Marry, John
答案 0 :(得分:8)
您可以创建一个2D数组,并基于位于索引points
的{{1}}来sort
。然后使用map
获取索引为1
的名称
0
如果所有这些数组都放在单独的变量中,则可以这样创建2D数组:
let array = [
["Sara", "24"],
["John", "12"],
["Eddi", "20"],
["Marry", "13"]
]
const sortedNames = array.sort((a, b) => b[1] - a[1])
.map(a => a[0])
console.log(sortedNames.join())
答案 1 :(得分:1)
1
索引的排序Array#map
let groupRank = [];
userA = ["Sara", "24"];
userB = ["John", "12"];
userC = ["Eddi", "20"];
userD = ["Marry", "13"];
var res = [userA,userB,userC,userD]; //group all in one
res = res.sort((a,b)=> b[1]-a[1]); // sort based on point
res = res.map(a=> a[0]); //map the names only
console.log(res)
答案 2 :(得分:1)
您可以使用sort
函数并将所有用户放在一个数组中。然后使用排序功能,并在排序时使用一元运算符将指针转换为数字。 sort
将给出一个数组数组。如果需要名称,请使用map
函数获取名称数组
let groupRank = [];
let userA = ["Sara", "24"];
let userB = ["John", "12"];
let userC = ["Eddi", "20"];
let userD = ["Marry", "13"];
let allUsers = [userA, userB, userC, userD];
groupRank = allUsers.sort(function(a, b) {
return +b[1] - (+a[1])
}).map(item => item[0])
console.log(groupRank)