Sam
Sam

Reputation: 63

AngularJS sorting a list with nulls

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

Upvotes: 3

Views: 4414

Answers (1)

Chandermani
Chandermani

Reputation: 42669

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.

Upvotes: 2

Related Questions