-1

I'd like to sort numbers and strings like this article: Sort strings and numbers in Ruby

And I prepared the following method to compare values.

# This method is expected to work Ruby's `<=>`.
compare: (x, y) ->
  if x < y then -1 else if x > y then 1 else 0

But JavaScript's comparison works different from Ruby's one.

x = [1, 11]
y = [1, 2]

compare(x, y)
# it expected to return 1 (means [1, 11] > [1, 2])
# but it returns -1 (means [1, 2] > [1, 11])

Though 11 is obviously greater that 2, array's second value seems not to be compared correctly.

Could you tell me what's wrong?

3
  • 1
    Why not show us your compare() function instead of pseudo-coding it for us? Commented Apr 16, 2016 at 12:24
  • It's impossible for us to know how your x < y works. Commented Apr 16, 2016 at 12:29
  • Code shown doesn't make sense in javascript. Please see minimal reproducible example. Why are you searching for ruby methods and not searching for javascript ones? Commented Apr 16, 2016 at 12:30

2 Answers 2

1

In Javascript Array#sort sorts by strings.

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. [Emphasis by NS]

Example with sort() and sort with callback by Numbers.

var array = [1, 2, 11, 20];

array.sort();
document.write('<pre>' + JSON.stringify(array, 0, 4) + '</pre>');

array.sort(function (a, b) { return a - b; });
document.write('<pre>' + JSON.stringify(array, 0, 4) + '</pre>');

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

Comments

0

You are trying to compare the array values not the contents of the array. You have to make decision on what to do with arrays of different length and loop over the values and compare them.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.