``````// 对一个名字数组进行排序
names.sort();

// 通过 name 对一个对象数组进行排序
users.sort(function (a, b) {
if (a.name < b.name) {
return -1;
}
if (a.name > b.name) {
return 1;
}
return 0;
});
``````

## 如何按字母顺序对一个名字数组进行排序

``````let names  = ["John Doe", "Alex Doe", "Peter Doe", "Elon Doe"];
``````

``````let sortedNames = names.sort();
console.log(sortedNames);
``````

``````["Alex Doe","Elon Doe","John Doe","Peter Doe"]
``````

``````let names = ["John Doe", "alex Doe", "peter Doe", "Elon Doe"];
let sortedNames = names.sort();

console.log(sortedNames); // ["Elon Doe","John Doe","alex Doe","peter Doe"]
``````

## 如何在 JavaScript 中按姓名的字母顺序排列

``````let users = [
{
name: "John Doe",
age: 17
},
{
name: "Elon Doe",
age: 27
},
{
name: "Alex Doe",
age: 14
}
];
``````

``````function(a, b){return a - b}
``````

• 如果结果是负的，`a` 被排序在 `b` 之前。
• 如果结果是正数，则 `b` 被排序在 `a` 之前。
• 如果结果是 `0`，两个值的排序顺序不做任何改变。

``````users.sort(function (a, b) {
if (a.name < b.name) {
return -1;
}
if (a.name > b.name) {
return 1;
}
return 0;
});

console.log(users);
``````

``````[
{
name: "Alex Doe",
age: 14
},
{
name: "Elon Doe",
age: 27
},
{
name: "John Doe",
age: 17
}
]
``````

``````let users = [
{
name: "alex Doe",
age: 14
},
{
name: "Elon Doe",
age: 27
},
{
name: "John Doe",
age: 17
}
];

users.sort(function (a, b) {
if (a.name < b.name) {
return -1;
}
if (a.name > b.name) {
return 1;
}
return 0;
});

console.log(users);
``````

``````[
{
name: "Elon Doe",
age: 27
},
{
name: "John Doe",
age: 17
},
{
name: "alex Doe",
age: 14
}
]
``````

Happy coding!