Error in ordering positive and negative numbers Jasvascript

3

I have an array with multiple numbers, these numbers are positive, negative and with decimal too:

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

I need to sort this array from MINOR to the LARGEST . The result you would expect 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 sort:

GraphOne[Regional].sort(function(a,b){return a > b});
    
asked by anonymous 21.11.2016 / 19:22

2 answers

6

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

In the case, for them 1,100 = a comma one, while for us would be one thousand and one 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);

Give the correct result. I hope the confusion that was occurring was clear.

    
21.11.2016 / 19:28
2

You will have to remove decimal points from all values in the array so you can consider it as an integer. For this you can use the Array # map , within the function by converting each number to string, changing . by empty, and then converting 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);
    
21.11.2016 / 19:46