How to sort an array of objects based on a key in typescript

I have a candidate object with properties

candidateid:number;
name:string;

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

+4
source share
1 answer

This is the same as regular old javascript. You can use the 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))
+8
source

Source: https://habr.com/ru/post/1656686/


All Articles