gpt4 book ai didi

javascript - 排序值不在我在 map 中使用排序的地方

转载 作者:行者123 更新时间:2023-12-03 16:48:46 25 4
gpt4 key购买 nike

我试过下面的代码变量数据 =

[{"name":"ramu","id":"719","gmail":"ramu@gmail.com","ph":988989898,"points":36},
{"name":"ravi","id":"445","gmail":"ravi@gmail.com","ph":4554545454,"points":122},
{"name":"karthik","id":"866","gmail":"karthik@gmail.com","ph":2332233232,"points":25}];
var names = data.map(s=>s.name.sort());
console.log(names);

错误:TypeError:s.name.sort 不是函数

但预期输出是 ["karthik","ramu", "ravi"]

最佳答案

尝试

var names = data.map(s=>s.name).sort(); //just move the sort out

演示

var data = [{
"name": "ramu",
"id": "719",
"gmail": "ramu@gmail.com",
"ph": 988989898,
"points": 36
},
{
"name": "ravi",
"id": "445",
"gmail": "ravi@gmail.com",
"ph": 4554545454,
"points": 122
},
{
"name": "karthik",
"id": "866",
"gmail": "karthik@gmail.com",
"ph": 2332233232,
"points": 25
}
];
//var names = data.map(s=>s.name).sort(); //just move the sort out
var names = data.map(s => s.name).sort((a, b) => a.localeCompare(b)); //used localeCompare instead of simple sort

console.log(names);

关于javascript - 排序值不在我在 map 中使用排序的地方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47328409/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com