I am using underscore to sort an array. Is there a way to make nulls always last whether ascending or descending? For example:
[
{ name: 'a', age: 1 },
{ name: 'z', age: 5 },
{ name: '', age: 1 },
{ name: 'v', age: 7 }
]
Will produce
[
{ name: 'a', age: 1 },
{ name: 'v', age: 7 },
{ name: 'z', age: 5 },
{ name: '', age: 1 }
]
and descending will produce:
[
{ name: 'z', age: 5 },
{ name: 'v', age: 7 },
{ name: 'a', age: 1 },
{ name: '', age: 1 }
]
My real array is an array of objects so i have to pluck values out.
There are many ways to go about it but you could try something like this:
var arr = [{name: 'a', age: 1}, {name: 'z', age: 5}, {name: '', age: 1}, {name: 'v', age: 7 }];
_.chain(arr)
.sortBy('name')
//.reverse() // to sort descending
.partition('name')
.flatten()
.value();
Result:
[ { name: 'a', age: 1 },
{ name: 'v', age: 7 },
{ name: 'z', age: 5 },
{ name: '', age: 1 } ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With