How to sort array containing list of object by object property value?
For example, we have a list of user object and we want to sort it by user name:
const users = [
{ firstname: 'Vincent', lastName: 'Vega',},
{ firstname: 'Jules', lastName: 'Winnfield', },
{ firstname: 'Butch', lastName: 'Coolidge', },
{ firstname: 'Mia', lastName: 'Wallace', },
];
and now we want to sort this list by user firstname - we will use method sort():
users.sort((a: User, b: User) => {
return a.firstname.localeCompare(b.firstname);
});
and now we have array sorted alphabetically by object property: firstname.
And now our user array will look like this:
[
{ firstname: 'Butch', lastName: 'Coolidge' },
{ firstname: 'Jules', lastName: 'Winnfield' },
{ firstname: 'Mia', lastName: 'Wallace' },
{ firstname: 'Vincent', lastName: 'Vega' }
]
so, the full typescript code for sorting array of object by object property value will look like this:
export interface User{
firstname: string,
lastName: string
}
const users = [
{
firstname: 'Vincent',
lastName: 'Vega',
},
{
firstname: 'Jules',
lastName: 'Winnfield',
},
{
firstname: 'Butch',
lastName: 'Coolidge',
},
{
firstname: 'Mia',
lastName: 'Wallace',
},
];
users.sort((a: User, b: User) => {
return a.firstname.localeCompare(b.firstname);
});
console.log(users);