简体   繁体   中英

How to sort array of numbers that includes negative values using localecompare?

I am trying to sort an array from lowest to highest value.

the example below shows it already sorted in this manner

var array = ["-394","-275","-156","-37","82","201","320","439","558","677","796"];

However when I do this:

 var array = ["-394", "-275", "-156", "-37", "82", "201", "320", "439", "558", "677", "796"]; array.sort(function(a, b) { return a.localeCompare(b, undefined, { numeric: true }) }); console.log(array); 

This is returned (i'm not sure what sorting has occurred):

["-37", "-156", "-275", "-394", "82", "201", "320", "439", "558", "677", "796"]

I've looked at:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare

but it doesn't seem to mentioned anything specifically about handling negative numbers.

What is the correct way to sort an array of numbers that includes negative values?

Because your array items can be coerced to numbers directly, why not do that instead?

 var array = ["-394","-275","-156","-37","82","201","320","439","558","677","796"]; array.sort(function(a,b) { return a - b } ); console.log(array); 

The a - b , which uses the subtraction operator, will coerce the expressions on both sides to numbers.

Numeric collation unfortunately does not take into account - signs. Your current code results in the sorter sorting - numbers before the numbers without - before them (because - comes before numbers, lexiographically).

 console.log('-'.charCodeAt()); console.log('0'.charCodeAt()); 

So with

  "-37",
  "-156",
  "-275",
  "-394",

37 comes before 156, which comes before 275, which comes before 394. (The same thing is happening with the positive numbers, they just all come afterwards).

Just use sort - all your items can be implicitly converted to numbers.

 var array = ["-394","-275","-156","-37","82","201","320","439","558","677","796"]; const res = array.sort((a, b) => a - b); console.log(res); 
 .as-console-wrapper { max-height: 100% !important; top: auto; } 

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