3

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?

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

interestingly i was actually trying to find "the value closeset to zero" (the negative value closest to zero in this case) in the array (the localeCompare step was just one step in that process), so the "unexpected sorting" that results from "doing it the wrong way" seems to provide a way for me to get the desired value by referencing the first value of the "incorrectly" sorted array. the lexicographic sorting seems to put the value closest to zero (including negative values) at the beginning of the array. i'm sure there is a better way of doing that, but still good to know.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.