我正在使用Angular 7,需要对多维数组进行排序。我有一个框,用户可以在其中选择国籍。我有一个Country[]
界面,在CountryCode
和CountryName
内有两个字段。
我想按CountryName
进行排序,我的用户将可以按照正确的字母顺序选择国籍。我看到Pipes
和Lodash librairy
可以帮助我创建自定义管道。
这是从数据库中获取CountryCode
和CountryName
的实际代码
private getCountryData() {
this.findAllCountries().subscribe((countries: Country[]) => {
this.countryList = country;
});
现在我对Lodash的尝试
transform(value: Country[], by: string, direction = "asc" | "desc"): Country[] {
this.countryList = _.orderBy(this.countryList, ['string', 'countryLabel'], ['asc', 'desc']);
return this.countryList;
}
谢谢!
答案 0 :(得分:1)
您不需要lodash
,可以使用JavaScript进行排序,如下所示。
var countries = [
{name: 'India', code: 'IN'},
{name: 'France', code: 'FR'},
{name: 'Australia', code: 'AU'},
];
var sorted = countries.sort((a, b) => a.name.localeCompare(b.name));
console.log(sorted);
答案 1 :(得分:0)
df['d'] = (df.sort_values(['b','a'])['c']
.where(df['a'].eq(df.groupby('b')['a'].transform('min'))).ffill())
let asc = "ASC";
let desc = "DESC";
let direction = "DESC";
let countries: Country[] = [{
CountryCode: "IN",
CountryName: "INDIA"
},
{
CountryCode: "US",
CountryName: "UNITED STATES"
},
{
CountryCode: "UK",
CountryName: "ENGLAND"
}
];
if (direction == "ASC") {
countries.sort((a, b) => (a.CountryName > b.CountryName) ? 1 : -1)
} else {
countries.sort((a, b) => (a.CountryName > b.CountryName) ? -1 : 1)
}
countries.forEach(item => {
console.log(item.CountryName);
});