我有一个对象数组,每个对象都有一个属性 name ,一个字符串。我想通过这个属性对数组进行排序。我希望他们按以下方式排序..
I've got an array of objects, each of which has a property name, a string. I'd like to sort the array by this property. I'd like them sorted in the following way..
`ABC` `abc` `BAC` `bac` etc...我怎么样?在JavaScript中实现这一点?
How would I achieve this in JavaScript?
推荐答案有两种基本方法:
var arr = [{name:"ABC"},{name:"BAC"},{name:"abc"},{name:"bac"}]; arr.sort(function(a,b){ var alc = a.name.toLowerCase(), blc = b.name.toLowerCase(); return alc > blc ? 1 : alc < blc ? -1 : 0; });或
arr.sort(function(a,b){ return a.name.toLowerCase().localeCompare(b.name.toLowerCase()); });请注意第二个版本忽略变音符号,所以 a 和à将按相同的字母排序。
Be aware that the 2nd version ignore diacritics, so a and à will be sorted as the same letter.
现在这两种方式的问题是他们不会在小写 abc 之前对大写 ABC 进行排序,因为它会将它们视为相同。
Now the problem with both these ways is that they will not sort uppercase ABC before lowercase abc, since it will treat them as the same.
要解决这个问题,你必须这样做:
To fix that, you will have to do it like this:
arr.sort(function(a,b){ var alc = a.name.toLowerCase(), blc = b.name.toLowerCase(); return alc > blc ? 1 : alc < blc ? -1 : a.name > b.name ? 1 : a.name < b.name ? -1 : 0; });再次在这里你可以选择使用 localeCompare 相反,如果你不希望变音符号影响这样的排序:
Again here you could choose to use localeCompare instead if you don't want diacritics to affect the sorting like this:
arr.sort(function(a,b){ var lccomp = a.name.toLowerCase().localeCompare(b.name.toLowerCase()); return lccomp ? lccomp : a.name > b.name ? 1 : a.name < b.name ? -1 : 0; });您可以在此处阅读有关排序的更多信息: developer.mozilla/en/JavaScript/Reference/Global_Objects/Array/sort
You can read more about sort here: developer.mozilla/en/JavaScript/Reference/Global_Objects/Array/sort