How to sort object array based on key in typescript

JavascriptArraysAngularTypescriptSorting

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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))

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionManoharView Question on Stackoverflow
Solution 1 - JavascripttoskvView Answer on Stackoverflow