2

I have a value function which is passed into my orderBy as:

function getValue(item){
    return [parseInt(item.approx_value_usd) || -1];
}

This definitely always returns a number array, but for some reason on the front-end AngularJS always orders my items by lexicographical order of the property 'approx_value_usd' e.g.

88 > 82 > 8 > 53 (wrong!)

I feel like I'm missing something but can't seem to get anywhere with this problem.

Tito
  • 832
  • 10
  • 24
  • No, it definitely always returns an array. – Pointy Apr 05 '15 at 20:45
  • @Pointy true, but that doesn't help – Tito Apr 05 '15 at 20:48
  • How do you know? Have you tried it without the `[ ]`? (Why are they there anyway?) When you involve an array in a `>` or `<` comparison, it gets converted to a string based on the values of its elements. – Pointy Apr 05 '15 at 20:49
  • 1
    Try `[8] > [53]` in your browser console. – Pointy Apr 05 '15 at 20:51
  • Oh wait.... that did in fact solve the issue. Sorry! Wow, thanks. Would it be possible to then order by a secondary value also? i.e. first by x then by y if x is equal (as I've used elsewhere with arrays). – Tito Apr 05 '15 at 20:53
  • Well with the Angular order-by mechanism, I'm not sure how you'd do that. – Pointy Apr 05 '15 at 20:55
  • There's [this question](http://stackoverflow.com/questions/17037524/orderby-multiple-fields-in-angular), but it seems to only involve sorting by the default ordering. – Pointy Apr 05 '15 at 20:56
  • Hm okay thanks. Something to look at later, but for now this works a charm. Feel free to add a brief answer and I'll accept it. May be useful to others. – Tito Apr 05 '15 at 21:06

1 Answers1

2

The return value of the "order-by" function is examined using simple comparisons. Your code is returning an array, not just a number. When an array appears in a JavaScript > or < comparison, it'll be converted to a string. That's done by taking the string value of each element in the array and joining them.

Thus, even though you were putting numbers in the array, when Angular actually used the returned value it ends up being a string anyway. If you drop the [ ] it should work.

Pointy
  • 405,095
  • 59
  • 585
  • 614