3

I have a scope object that has a list containing null values, I would like to sort this list in both directions but the null values must be always at the end. I can probably do this easily by splitting up the object into 2, one with nulls and one without then stick on the null list at the end. But is there a more efficient way to do this?

example:

[1,null,5,7,2,null]

sorted:

ASD: 1,2,5,7,null,null

DESC: 7,5,2,1,null,null
cuongle
  • 74,024
  • 28
  • 151
  • 206
Sam
  • 63
  • 1
  • 3

1 Answers1

2

If you just want to sort the array, JavaScript has method array.sort. This takes a comparer function.

You can implement two of such functions one for ascending sorting and one for descending. Within these two functions you can treat nulls as you wish. See documentation here

If you are using angularjs filter orderby it too takes a comparer function, so a similar approach may work.

Chandermani
  • 42,589
  • 12
  • 85
  • 88
  • you cannot orderby without replacing the null values, it will break, as you cannot have duplicates in the item list, when using it in combination with ng-repeat. – Florian Aug 06 '13 at 06:27
  • Duplicate issue is with ng-repeat not orderby fiter that i know of. Why should orderby fail on duplicate values? – Chandermani Aug 06 '13 at 06:33
  • had to add the "in combination with ng-repeat" - in itself, using orderby is fine, but you will run into problems when displaying the items. however, i think this is the right answer for the case described. – Florian Aug 06 '13 at 06:50
  • 2
    You can have duplicates in an `ngRepeat` if you specify `track by $index` at the end of your repeater expression. – Steve Klösters Aug 06 '13 at 11:21
  • Problem is that the orderBy predicate is used to return the value to sort by and is not itself a comparator function i.e. the problem as described where `null` values are always at the bottom/end of the list isn't addressed. Here is a plunk showing the behaviour: http://embed.plnkr.co/GCpQGe/preview – craigb May 07 '14 at 21:26