我有一个对象列表,我希望基于类型字符串的字段attr进行排序。我试着用

list.sort(function (a, b) {
    return a.attr - b.attr
})

但发现-似乎不适用于JavaScript中的字符串。我如何能排序基于类型字符串的属性的对象列表?


当前回答

为什么问题中的方法不起作用的解释:

let products = [
    { name: "laptop", price: 800 },
    { name: "phone", price:200},
    { name: "tv", price: 1200}
];
products.sort( (a, b) => {
    {let value= a.name - b.name; console.log(value); return value}
});

> 2 NaN

字符串之间的减法返回NaN。

附和@Alejadro的回答,正确的方法是——

产品。排序(a,b) => a。一、二、三)

其他回答

按照你的例子使用String.prototype.localeCompare:

list.sort(function (a, b) {
    return ('' + a.attr).localeCompare(b.attr);
})

我们强制a.attr为字符串以避免异常。从Internet Explorer 6和Firefox 1开始就支持localeCompare。你可能还会看到下面的代码不尊重区域设置:

if (item1.attr < item2.attr)
  return -1;
if ( item1.attr > item2.attr)
  return 1;
return 0;

这里应该使用>或<和==。所以解决方案是:

list.sort(function(item1, item2) {
    var val1 = item1.attr,
        val2 = item2.attr;
    if (val1 == val2) return 0;
    if (val1 > val2) return 1;
    if (val1 < val2) return -1;
});
list.sort(function(item1, item2){
    return +(item1.attr > item2.attr) || +(item1.attr === item2.attr) - 1;
}) 

他们如何工作样本:

+('aaa'>'bbb')||+('aaa'==='bbb')-1
+(false)||+(false)-1
0||0-1
-1

+('bbb'>'aaa')||+('bbb'==='aaa')-1
+(true)||+(false)-1
1||0-1
1

+('aaa'>'aaa')||+('aaa'==='aaa')-1
+(false)||+(true)-1
0||1-1
0

更新答案(2014年10月)

我真的很讨厌这个字符串自然排序顺序,所以我花了一些时间来调查这个问题。

长话短说

localeCompare()字符支持是坏蛋,使用它。 正如Shog9所指出的,你的问题的答案是:

return item1.attr.localeCompare(item2.attr);

在所有自定义JavaScript“自然字符串排序顺序”实现中发现的错误

有相当多的自定义实现,试图进行字符串比较更精确地称为“自然字符串排序顺序”

当“玩”这些实现时,我总是注意到一些奇怪的“自然排序顺序”选择,或者说是错误(最好的情况下是遗漏)。

通常,特殊字符(空格、破折号、&号、括号等)不会被正确处理。

然后你会发现它们出现在不同的地方,通常情况下可能是:

有些介于大写字母Z和小写字母a之间 有些介于9和大写的A之间 有些会在小写z后面

当人们期望所有特殊字符都“分组”在一个地方时,除了空格特殊字符maybe(它总是第一个字符)。也就是说,要么全部在数字之前,要么全部在数字和字母之间(小写字母和大写字母一个接一个“在一起”),要么全部在字母之后。

我的结论是,当我开始添加几乎不寻常的字符(即带有变音符的字符或像破折号、感叹号等字符)时,它们都不能提供一致的顺序。

自定义实现研究:

Natural Compare Lite https://github.com/litejs/natural-compare-lite : Fails at sorting consistently https://github.com/litejs/natural-compare-lite/issues/1 and http://jsbin.com/bevututodavi/1/edit?js,console, basic Latin characters sorting http://jsbin.com/bevututodavi/5/edit?js,console Natural Sort https://github.com/javve/natural-sort : Fails at sorting consistently, see issue https://github.com/javve/natural-sort/issues/7 and see basic Latin characters sorting http://jsbin.com/cipimosedoqe/3/edit?js,console JavaScript Natural Sort https://github.com/overset/javascript-natural-sort: seems rather neglected since February 2012, Fails at sorting consistently, see issue https://github.com/overset/javascript-natural-sort/issues/16 Alphanum http://www.davekoelle.com/files/alphanum.js , Fails at sorting consistently, see http://jsbin.com/tuminoxifuyo/1/edit?js,console

通过localeCompare()实现浏览器的本地“自然字符串排序顺序”

localeCompare()最老的实现(没有locale和options参数)被Internet Explorer 6及更高版本所支持,请参阅http://msdn.microsoft.com/en-us/library/ie/s4esdbwz(v=vs.94).aspx(向下滚动到localeCompare()方法)。

内置的localeCompare()方法在排序方面做得更好,甚至是国际字符和特殊字符。

使用localeCompare()方法的唯一问题是“使用的语言环境和排序顺序完全依赖于实现”。换句话说,当使用localeCompare(如stringOne.localeCompare(stringTwo))时:Firefox、Safari、Chrome和Internet Explorer对字符串有不同的排序顺序。

浏览器原生实现研究:

http://jsbin.com/beboroyifomu/1/edit?js,console - basic Latin characters comparison with localeCompare() http://jsbin.com/viyucavudela/2/ - basic Latin characters comparison with localeCompare() for testing on Internet Explorer 8 http://jsbin.com/beboroyifomu/2/edit?js,console - basic Latin characters in string comparison : consistency check in string vs when a character is alone https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare - Internet Explorer 11 and later supports the new locales & options arguments

“字符串自然排序顺序”的难点

实现一个可靠的算法(意思是:一致但也涵盖广泛的字符)是一项非常艰巨的任务。UTF-8包含2000多个字符,涵盖120多种脚本(语言)。

最后,这个任务有一些规范,它被称为“Unicode Collation Algorithm”,可以在http://www.unicode.org/reports/tr10/上找到。关于这个问题,你可以在https://softwareengineering.stackexchange.com/questions/257286/is-there-any-language-agnostic-specification-for-string-natural-sorting-order上找到更多信息

最终结论

因此,考虑到目前我遇到的JavaScript自定义实现所提供的支持级别,我们可能永远不会看到任何东西接近于支持所有这些字符和脚本(语言)。因此,我宁愿使用浏览器的本地localeCompare()方法。是的,它确实有在不同浏览器之间不一致的缺点,但基本测试表明,它涵盖了更广泛的字符范围,允许稳定和有意义的排序顺序。

正如Shog9所指出的,你的问题的答案是:

return item1.attr.localeCompare(item2.attr);

进一步阅读:

https://softwareengineering.stackexchange.com/questions/257286/is-there-any-language-agnostic-specification-for-string-natural-sorting-order How to sort strings in JavaScript Natural sort of alphanumerical strings in JavaScript Sort Array of numeric & alphabetical elements (Natural Sort) Sort mixed alpha/numeric array https://web.archive.org/web/20130929122019/http://my.opera.com/GreyWyvern/blog/show.dml/1671288 https://web.archive.org/web/20131005224909/http://www.davekoelle.com/alphanum.html http://snipplr.com/view/36012/javascript-natural-sort/ http://blog.codinghorror.com/sorting-for-humans-natural-sort-order/

多亏了Shog9的回答,让我找到了我相信的“正确”方向。

嵌套三元箭头函数

(a,b) => (a < b ? -1 : a > b ? 1 : 0)