在Javascript中按名字(按字母顺序)对数组进行排序 [英] Sort array by firstname (alphabetically) in Javascript
问题描述
我有一个数组(请参阅下面的数组中的一个对象),我需要使用JavaScript对firstname进行排序。
我该怎么办?
I got an array (see below for one object in the array) that I need to sort by firstname using JavaScript. How can I do it?
var user = {
bio: null,
email: "user@domain.com",
firstname: "Anna",
id: 318,
lastAvatar: null,
lastMessage: null,
lastname: "Nickson",
nickname: "anny"
};
推荐答案
假设你有一个数组用户
。你可以使用 users.sort
并传递一个带两个参数的函数并比较它们(比较器)
Suppose you have an array users
. You may use users.sort
and pass a function that takes two arguments and compare them (comparator)
它应该返回
- 如果第一个参数小于秒,则应为负数(应放在结果数组中的第二个参数之前)
- 如果第一个参数更大(应该放在第二个参数之后),则为正数
- 0如果这两个元素相等。
在我们的例子中,如果两个元素是 a
和 b
我们想要比较 a.firstname
和 b.firstname
In our case if two elements are a
and b
we want to compare a.firstname
and b.firstname
示例:
users.sort(function(a, b){
if(a.firstname < b.firstname) { return -1; }
if(a.firstname > b.firstname) { return 1; }
return 0;
})
此代码适用于任何类型。
This code is going to work with any type.
请注意,在现实生活中 ™你经常想忽略大小写,正确排序diacr比较字符串时,itics,奇怪的符号如ß等,所以你可能想要使用 localeCompare
。为清楚起见,请参阅其他答案。
Note that in "real life"™ you often want to ignore case, correctly sort diacritics, weird symbols like ß, etc when you compare strings, so you may want to use localeCompare
. See other answers for clarity.
这篇关于在Javascript中按名字(按字母顺序)对数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!