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?
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 .
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.
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 });
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With