本文共 2544 字,大约阅读时间需要 8 分钟。
本文翻译自:
I got an array (see below for one object in the array) that I need to sort by firstname using JavaScript. 我有一个数组(请参阅下面的数组中的一个对象),我需要使用JavaScript对firstname进行排序。 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"};
参考:
If compared strings contain unicode characters you can use of String
class like the following: 如果比较字符串包含unicode字符,则可以使用String
类的 ,如下所示:
users.sort(function(a,b){ return a.firstname.localeCompare(b.firstname);})
offers the very nice _.sortBy function: 提供了非常好的_.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()})
A more compact notation: 更紧凑的符号:
user.sort(function(a, b){ return a.firstname === b.firstname ? 0 : a.firstname < b.firstname ? -1 : 1;})
You can use the in-built array method - sort
. 您可以使用内置数组方法 - sort
。 This method takes a callback method as a param 此方法将回调方法作为参数
// custom sort function to be passed as param/callback to the Array's sort method function myCustomSort(a, b) { return (a.toLowerCase() > b.toLowerCase()) ? 1 : -1; } // Actual method to be called by entity that needs sorting feature function sortStrings() { var op = Array.prototype.sort.call(arguments, myCustomSort); } // Testing the implementation var sortedArray = sortStrings("Burger", "Mayo1", "Pizza", "boxes", "Apples", "Mayo"); console.log(sortedArray); //["Apples", "boxes", "Burger", "Mayo", "Mayo1", "Pizza"]
Key Points to be noted for understanding this code. 理解此代码需要注意的要点。
myCustomSort
, should return +1 or -1 for each element pair(from the input array) comparison. 自定义方法(在本例中为myCustomSort
)应为每个元素对(来自输入数组)的比较返回+1或-1。 toLowerCase()
/ toUpperCase()
in the custom sorting callback method so that case difference does not affect the correctness of the sorting process. 在自定义排序回调方法中使用toLowerCase()
/ toUpperCase()
,以便大小写差异不会影响排序过程的正确性。 I hope this is clear enough explanation. 我希望这是足够明确的解释。 Feel free to comment if you think, more info is needed. 如果您认为,请随时发表评论,需要更多信息。
Cheers! 干杯!
You can use something similar, to get rid of case sensitive 您可以使用类似的东西来摆脱区分大小写
users.sort(function(a, b){ //compare two values if(a.firstname.toLowerCase() < b.firstname.toLowerCase()) return -1; if(a.firstname.toLowerCase() > b.firstname.toLowerCase()) return 1; return 0;})
转载地址:http://vscnb.baihongyu.com/