Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make nulls always last when sorting

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.

like image 554
Luke101 Avatar asked Mar 17 '23 19:03

Luke101


1 Answers

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 } ]
like image 147
istos Avatar answered Mar 29 '23 18:03

istos