How to sort an array of objects using Typescript?

Asked

Viewed 1,883 times

1

I got the following array:

public arr = [ 
    { id: 1, name: 'João das Neves'},
    { id: 2, name: 'Areia Stark'},
    { id: 3, name: 'Sonsa Stark'}    
];

I’d like to order that array by the attribute name, thus remaining:

public arr = [ 
    { id: 2, name: 'Areia Stark'},
    { id: 1, name: 'João das Neves'},        
    { id: 3, name: 'Sonsa Stark'}    
];

How to order a array of objects using Typescript?

  • I like the names in the :D array

  • Why "using Typescript"? It wouldn’t be the same if using Javascript normally?

1 answer

3

You can use the .Sort() for that reason:

arr.sort((a, b) => (a.name < b.name) ? -1 : 1);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.