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
0

1 Answer 1

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.

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

5 Comments

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.
Duplicate issue is with ng-repeat not orderby fiter that i know of. Why should orderby fail on duplicate values?
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.
You can have duplicates in an ngRepeat if you specify track by $index at the end of your repeater expression.
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: embed.plnkr.co/GCpQGe/preview

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.