简体   繁体   中英

Javascript Array Sort function not sorting properly

I have a question regarding javascript's sort() function

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] ?

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.

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

The sorting of number is based on 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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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