mian mian - 5 months ago 10
Javascript Question

How to sort array by two properties - alphabetically but null values at the end?

I have an array which contains objects.

Those objects have a fullname property and an member-id.

While the fullname is always available the member-id can be null if he or she is a potential member but has not signed up yet.

The result should look as follows:

{ id: 1122, name: Adrianna Budzinski }
{ id: 3785, name: Amy Divine }
{ id: 1555, name: Gale Purdue }
{ id: 1920, name: Rex Feng }
{ id: 2010, name: Samella Vizcaino }
{ id: null, name: Bethanie Weaver }
{ id: null, name: Celesta Gullo }
{ id: null, name: Darrick Fort }
{ id: null, name: Edmundo Boulanger }
{ id: null, name: Freddie Lanclos }
{ id: null, name: Gregory Lickteig }
{ id: null, name: Gwendolyn Cuadra }
{ id: null, name: Krystal Brosnahan }
{ id: null, name: Lahoma Pagani }
{ id: null, name: Senaida Risk }
{ id: null, name: Valarie Lopes }


The members with an id should be at the top sorted by name and the members without should follow also sorted by name.

What I achieved so far are two separate sort functions but I do not know how to merge them.

let sortedFriends = friends.sort(function(a, b){
if(a.name < b.name) return -1;
if(a.name > b.name) return 1;
return 0;
});

sortedFriends = sortedFriends.sort(function(a, b){
if(a.id === null) return 1;
if(b.id === null) return -1;
if(a.id === b.id) return 0;
if(a.id < b.id) return -1 ;
if(a.id < b.id) return 1;
});

Answer

You could use sort by groups (id or null) and by name.

var array = [{ id: null, name: 'Darrick Fort' }, { id: null, name: 'Edmundo Boulanger' }, { id: 1122, name: 'Adrianna Budzinski' }, { id: null, name: 'Freddie Lanclos' }, { id: null, name: 'Gregory Lickteig' }, { id: null, name: 'Gwendolyn Cuadra' }, { id: 2010, name: 'Samella Vizcaino' }, { id: null, name: 'Bethanie Weaver' }, { id: null, name: 'Celesta Gullo' }, { id: 3785, name: 'Amy Divine' }, { id: null, name: 'Krystal Brosnahan' }, { id: null, name: 'Lahoma Pagani' }, { id: 1920, name: 'Rex Feng' }, { id: 1555, name: 'Gale Purdue' }, { id: null, name: 'Senaida Risk' }, { id: null, name: 'Valarie Lopes' }];

array.sort(function (a, b) {
    return (a.id === null) - (b.id === null) || a.name.localeCompare(b.name);
});

console.log(array);

Comments