How to sort an array of objects using TypeScript?

1

I have the following array :

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

I would like to sort this array by the name attribute, thus:

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

How to sort a array of objects using TypeScript?

    
asked by anonymous 01.11.2017 / 13:09

1 answer

2

You can use .sort () to do this:

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