最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to sort array of numbers that includes negative values using localecompare? - Stack Overflow

programmeradmin2浏览0评论

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);

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

Share Improve this question edited Jul 2, 2019 at 3:59 Jack Bashford 44.1k11 gold badges55 silver badges82 bronze badges asked Jul 2, 2019 at 3:54 user1063287user1063287 10.9k27 gold badges140 silver badges237 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

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 - es before numbers, lexiographically).

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

So with

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

37 es before 156, which es before 275, which es before 394. (The same thing is happening with the positive numbers, they just all e 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; }

发布评论

评论列表(0)

  1. 暂无评论