Javascript 如何根据打字稿中的键对对象数组进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39850339/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:58:07  来源:igfitidea点击:

How to sort object array based on key in typescript

javascriptangulartypescript

提问by Manohar

I have a candidate object with properties

我有一个具有属性的候选对象

candidateid:number;
name:string;

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

我希望根据name属性对此类对象的数组进行排序。如何在 angular 2 的 TypeScript 中实现这一点?

回答by toskv

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

它与普通的旧 javascript 相同。您仍然可以使用箭头函数使其更简洁。

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

Or using localeCompare.

或者使用localeCompare

x.sort((a, b) => a.name.localeCompare(b.name))