简体   繁体   English

Javascript数组排序功能排序不正确

[英]Javascript Array Sort function not sorting properly

I have a question regarding javascript's sort() function我有一个关于 javascript 的 sort() 函数的问题

var arr = [23,43,54,2,3,12];
arr.sort();

it's output is [12, 2, 23, 3, 43, 54] well it should be [2, 3, 12, 23, 43, 54] ?它的输出是[12, 2, 23, 3, 43, 54]那么它应该是[2, 3, 12, 23, 43, 54]吗?

It's because you're sorting the numbers with the default sorting algorithm, which converts them to a string and sorts lexicographically. 这是因为您要使用默认的排序算法对数字进行排序,该算法会将它们转换为字符串并按字典顺序进行排序。

Instead pass a function defining a sort order via its return value. 而是通过其返回值传递定义排序顺序的函数。

 var arr = [23,43,54,2,3,12]; console.log(arr.sort((a, b) => a - b)); 

Returning a positive number moves a toward the end of the list. 返回正数将a移到列表的末尾。

You have to specify a sort function 您必须指定排序功能

[12, 2, 23, 3, 43, 54].sort(function (a, b) { return  a - b ; } )

The javascript specification states that sort should perform lexicografic sorting, docs javascript规范指出排序应执行词汇排序排序, docs

The sorting of number is based on Unicode. 数字排序基于Unicode。 Hence the oder you have is correct. 因此,您的建议是正确的。 Refer the link for details. 请参阅链接以获取详细信息。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

let arr = [23,43,54,2,3,12];让 arr = [23,43,54,2,3,12];

arr.sort((a, b) => { return a - b; // Ascending }); arr.sort((a, b) => { return a - b; // 升序 });

arr.sort((a, b) => { return b - a; // Descending }); arr.sort((a, b) => { return b - a; // 降序 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM