0

Why is this function returning elements sorted alphabetically rather than numerically? I get the identical results whether I use Number or ParseFloat.

function sortMe() {
  var x = ["1.0","2.5", "11.0"];
  var y = x.map(Number);
  Logger.log(y.sort());
}

Result: 1,11,2.5

Jeff Axelrod
  • 27,676
  • 31
  • 147
  • 246

4 Answers4

2

Because Array#sort sorts alphabetical, so '11' comes before '2'.

The sort() method sorts the elements of an array in place and returns the array. The sort is not necessarily stable. The default sort order is according to string Unicode code points.

To overcome this problem, you could use a numerical sort with a callback, like

array.sort(function (a, b) {
    return a - b;
});
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

That's because the default sort order is according to string Unicode code points, no matter what your input is. Your Number are implicitly converted back to strings and then sorted.

Oleg V. Volkov
  • 21,719
  • 4
  • 44
  • 68
0

Its not that you are unable to pass a numeric array, whatever you pass Array#sort will try to compare on the basis of their unicode representation. Instead pass a comparator, to compare how you want to compare while sorting

y.sort((a,b)=>a-b)
Koushik Chatterjee
  • 4,106
  • 3
  • 18
  • 32
-1

The sort() method sorts the items of an array.

The sort order can be either alphabetic or numeric, and either ascending (up) or descending (down).

By default, the sort() method sorts the values as strings in alphabetical and ascending order, with respect to each element's Unicode point value.

Have a look at this example:

var fruit = ['cherries', 'apples', 'bananas'];
fruit.sort(); // ['apples', 'bananas', 'cherries']

var scores = [1, 10, 21, 2]; 
scores.sort(); // [1, 10, 2, 21]
// Note that 10 comes before 2,
// because '10' comes before '2' in Unicode code point order.

var things = ['word', 'Word', '1 Word', '2 Words'];
things.sort(); // ['1 Word', '2 Words', 'Word', 'word']
// In Unicode, numbers come before upper case letters,
// which come before lower case letters.
Trishant Pahwa
  • 2,559
  • 2
  • 14
  • 31
  • Order can be either "default" or "whatever you program in your sort function". There's no special settings for "numeric" or "ascending/descending". – Oleg V. Volkov Aug 09 '17 at 09:12