Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort object array based on key in typescript [duplicate]

I have a candidate object with properties

candidateid:number; name:string; 

I wish to sort an array of such objects based on the name property. How can I achieve this in TypeScript in angular 2?

like image 851
Manohar Avatar asked Oct 04 '16 10:10

Manohar


People also ask

How do you sort an array of objects by key value?

To sort array on key value with JavaScript, we can use the array sort method. to call arr. sort with a callback that sort the entries by the name property lexically with localeCompare .

How do you sort an array based on an object's value in typescript?

Array. sort() function sorts an Array. The Sort() function will sort array using the optional compareFunction provided, if it is not provided Javascript will sort the array object by converting values to strings and comparing strings in UTF-16 code units order.

How do you sort a key value pair in typescript?

sort(function(a, b): any { const dateA = new Date(a['ActivationDate']); const dateB = new Date(b['ActivationDate']); console. log('dateA -' + dateA); console. log('dateB -' + dateB); console. log(dateB > dateA); return dateB > dateA; //sort by date decending });


1 Answers

It's the same as plain old javascript. You can still use an arrow function to make it more concise.

x.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0) 

Or using localeCompare.

x.sort((a, b) => a.name.localeCompare(b.name)) 
like image 184
toskv Avatar answered Sep 30 '22 09:09

toskv