Javascript 在Javascript中按名字(按字母顺序)对数组进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6712034/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sort array by firstname (alphabetically) in Javascript
提问by Jonathan Clark
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?
我得到了一个数组(数组中的一个对象见下文),我需要使用 JavaScript 按名字排序。我该怎么做?
var user = {
bio: null,
email: "[email protected]",
firstname: "Anna",
id: 318,
lastAvatar: null,
lastMessage: null,
lastname: "Nickson",
nickname: "anny"
};
回答by RiaD
Suppose you have an array users
. You may use users.sort
and pass a function that takes two arguments and compare them (comparator)
假设您有一个数组users
。您可以使用users.sort
并传递一个接受两个参数并比较它们的函数(比较器)
It should return
它应该返回
- something negative if first argument is less than second (should be placed before the second in resulting array)
- something positive if first argument is greater (should be placed after second one)
- 0 if those two elements are equal.
- 如果第一个参数小于第二个,则为负数(应放在结果数组中的第二个之前)
- 如果第一个参数更大,则为正数(应放在第二个参数之后)
- 如果这两个元素相等,则为 0。
In our case if two elements are a
and b
we want to compare a.firstname
and b.firstname
在我们的例子中,如果两个元素是a
并且b
我们想要比较a.firstname
和b.firstname
Example:
例子:
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.
此代码适用于任何类型。
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.
请注意,在“现实生活”中?在比较字符串时,您经常想忽略大小写、正确排序变音符号、像 ? 等奇怪的符号,因此您可能想要使用localeCompare
. 为清楚起见,请参阅其他答案。
回答by Nachiketha
Shortest possible code with ES6!
使用 ES6 的最短代码!
users.sort((a, b) => a.firstname.localeCompare(b.firstname))
String.prototype.localeCompare()basic support is universal!
String.prototype.localeCompare()基本支持是通用的!
回答by Mrchief
Something like this:
像这样的东西:
array.sort(function(a, b){
var nameA=a.name.toLowerCase(), nameB=b.name.toLowerCase();
if (nameA < nameB) //sort string ascending
return -1;
if (nameA > nameB)
return 1;
return 0; //default return value (no sorting)
});
回答by ovunccetin
If compared strings contain unicode characters you can use localeCompare
functionof String
class like the following:
如果比较的字符串包含 unicode 字符,您可以使用类的localeCompare
函数,String
如下所示:
users.sort(function(a,b){
return a.firstname.localeCompare(b.firstname);
})
回答by Sam Logan
Nice little ES6 one liner:
漂亮的小 ES6 单衬:
users.sort((a, b) => a.firstname !== b.firstname ? a.firstname < b.firstname ? -1 : 1 : 0);
回答by sumit
We can use localeCompare but need to check the keys as well for falsey values
我们可以使用 localeCompare 但也需要检查键是否为假值
The code below will not work if one entry has missing lname.
如果一个条目缺少 lname,下面的代码将不起作用。
obj.sort((a, b) => a.lname.localeCompare(b.lname))
So we need to check for falsey value like below
所以我们需要检查如下的 falsey 值
let obj=[
{name:'john',lname:'doe',address:'Alaska'},
{name:'tom',lname:'hopes',address:'California'},
{name:'harry',address:'Texas'}
]
let field='lname';
console.log(obj.sort((a, b) => (a[field] || "").toString().localeCompare((b[field] || "").toString())));
OR
或者
we can use lodash , its very simple. It will detect the returned values i.e whether number or string and do sorting accordingly .
我们可以使用 lodash ,它非常简单。它将检测返回的值,即是数字还是字符串,并进行相应的排序。
import sortBy from 'lodash/sortBy';
sortBy(obj,'name')
回答by Peter T.
underscorejsoffers the very nice _.sortBy function:
underscorejs提供了非常好的 _.sortBy 函数:
_.sortBy([{a:1},{a:3},{a:2}], "a")
or you can use a custom sort function:
或者您可以使用自定义排序功能:
_.sortBy([{a:"b"},{a:"c"},{a:"a"}], function(i) {return i.a.toLowerCase()})
回答by Emeeus
In case we are sorting names or something with special characters, like ?or áéíóú(commons in Spanish) we could use the params locales(esfor spanish in this case ) and optionslike this:
如果我们对名称或带有特殊字符的内容进行排序,例如? 或áéíóú(西班牙语中的常用语)我们可以使用 params语言环境(在本例中为es为西班牙语)和如下选项:
let user = [{'firstname': 'Az'},{'firstname': 'áb'},{'firstname':'ay'},{'firstname': '?a'},{'firstname': 'Nz'},{'firstname': 'ny'}];
user.sort((a, b) => a.firstname.localeCompare(b.firstname, 'es', {sensitivity: 'base'}))
console.log(user)
The oficial locale options could be found here in iana, es (spanish), de (German), fr (French). About sensitivitybasemeans:
官方语言环境选项可以在iana、 es (西班牙语)、 de (德语)、 fr (法语)中找到。关于灵敏度基础的意思是:
Only strings that differ in base letters compare as unequal. Examples: a ≠ b, a = á, a = A.
只有基本字母不同的字符串比较为不相等。示例:a ≠ b,a = á,a = A。
回答by James Andrews
A more compact notation:
更紧凑的符号:
user.sort(function(a, b){
return a.firstname === b.firstname ? 0 : a.firstname < b.firstname ? -1 : 1;
})
回答by Senad Me?kin
Basically you can sort arrays with method sort, but if you want to sort objects then you have to pass function to sort method of array, so I will give you an example using your array
基本上你可以用sort方法对数组进行排序,但是如果你想对对象进行排序,那么你必须将函数传递给数组的sort方法,所以我会给你一个使用你的数组的例子
user = [{
bio: "<null>",
email: "[email protected]",
firstname: 'Anna',
id: 318,
"last_avatar": "<null>",
"last_message": "<null>",
lastname: 'Nickson',
nickname: 'anny'
},
{
bio: "<null>",
email: "[email protected]",
firstname: 'Senad',
id: 318,
"last_avatar": "<null>",
"last_message": "<null>",
lastname: 'Nickson',
nickname: 'anny'
},
{
bio: "<null>",
email: "[email protected]",
firstname: 'Muhamed',
id: 318,
"last_avatar": "<null>",
"last_message": "<null>",
lastname: 'Nickson',
nickname: 'anny'
}];
var ar = user.sort(function(a, b)
{
var nA = a.firstname.toLowerCase();
var nB = b.firstname.toLowerCase();
if(nA < nB)
return -1;
else if(nA > nB)
return 1;
return 0;
});