Error sorting positive and negative numbers Jasvascript

Asked

Viewed 260 times

3

I have an array with several numbers, these numbers are positive, negative and decimal as well:

var array = [365, -1.304, -17.803, -3.529, -3.602, -2.942, -2.074, -115]

I need to sort this array of MINOR to the GREATER. The result that was to be expected is:

[-17.803, -3.602, -3.529, -2.942, -2.074, -1.304, -115, 365]

But instead this is coming out:

[-115, -17.803, -3.602, -3.529, -2.942, -2.074, -1.304, 365]

The code I’m using to order:

GraphOne[Regional].sort(function(a,b){return a > b});
  • @leofontes, but -17,803 is 17,000. So 17,000 is farther than -115

  • 1

    Man, are you using .. This is decimal separator

  • @Alissonacioli yes I had read in the English convention so it made sense my comment, but you’re thinking in Portuguese.

2 answers

6


You need to take the . of the numbers, Javascript uses the English convention in which the . is ours ,

In this case, for them 1,100 = a comma one, while for us it would be a thousand and a hundred.

var array = [365, -1304, -17803, -3529, -3602, -2942, -2074, -115];

console.log(array);

array.sort(function(a,b){return a > b});

console.log(array);

It gives the correct result. I hope it was clear the confusion that was occurring.

2

You will have to remove the decimal points from all values in the array in order to consider it as an integer. For this you can use the Array#map, within the function by converting each number into a string, swap . by empty, and then convert to number again.

var array = [365, -1.304, -17.803, -3.529, -3.602, -2.942, -2.074, -115].map(function(x) {
  x += '';
  return Number(x.replace('.', ''));
}).sort(function(a, b) {
  return a - b;
});

console.log(array);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.