[英]How to Sort String numbers using javascript
This is my data ["2","1","10"]
.这是我的数据
["2","1","10"]
。 When I am trying to sort these numbers my output is ["1","10","2"]
, but my expected output is ["1","2","10]
. I am using orderBy to sort these numbers. It sorts depending upon 0 to 9 only.当我尝试对这些数字进行排序时,我的输出是
["1","10","2"]
,但我的预期输出是["1","2","10]
。我正在使用 orderBy 对这些数字进行排序数字。它仅根据 0 到 9 进行排序。
How can I sort these numbers using js?如何使用js对这些数字进行排序?
Here is my code:这是我的代码:
ng-options="option.id as option.roomno for option in frData
| unique:'roomno' | orderBy:'roomno' "
function sortNumStr(m,n) {
return m - n;
}
var numArray = ["2", "1", "10"];
numArray.sort(sortNumStr);
alert(numArray)
You can use the string's native prototype localeCompare
function like so:您可以像这样使用字符串的原生原型
localeCompare
函数:
["2","1","10"].sort((a,b) => a.localeCompare(b, undefined, { numeric: true }))
It works well with numbers among other chars too.它也适用于其他字符中的数字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.