Last Updated: February 25, 2016
·
995
· wulab

Compare two numeric arrays in CoffeeScript

I was surprised that JavaScript convert all array elements to string before comparing them. This gives unexpected result in some cases.

coffee> [1,3] > [1,2]
true
coffee> [1,10] > [1,2]
false  # '10' < '2'

With the following addition to Array prototype:

Array::greaterThan = (otherArray) ->
  for element, index in @ when element isnt otherArray[index]
    return element > otherArray[index]
  false  # @ == otherArray

Now it behaves like what I had expected.

coffee> [1,10].greaterThan [1,2]
true

1 Response
Add your response

Nice, simple solution that can be easily adapted for lessThan and equals. Depending on your use case, you may want to add a check for array length, as

coffee> [0, 9].greaterThan [0, 8, 1]
true

Assuming you wanted to consider longer arrays to be greater, the following modification should work.

Array::greaterThan = (otherArray) ->
  thisLen = this.length
  otherLen = otherArray.length

  if thisLen isnt otherLen
    return thisLen > otherLen

  for element, index in @ when element isnt otherArray[index]
    return element > otherArray[index]
  false
over 1 year ago ·