84

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?

0

1 Answer 1

170

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))
Sign up to request clarification or add additional context in comments.

5 Comments

Or use localeCompare.
localeCompare - must have been a brit that wrote it... does not work in node fwi
Nested ternaries may be more concise, but they are harder to read.
I get in node js Property 'foo' does not exist on type 'object'.ts(2339)
@Jonathan do you know why it does not work in nodejs? node and browser js use the same js engine..

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.