Lodash顺序由按字母顺序排列的角度对象[]

时间:2020-02-05 15:42:11

标签: angular typescript sorting multidimensional-array lodash

我正在使用Angular 7,需要对多维数组进行排序。我有一个框,用户可以在其中选择国籍。我有一个Country[]界面,在CountryCodeCountryName内有两个字段。

我想按CountryName进行排序,我的用户将可以按照正确的字母顺序选择国籍。我看到PipesLodash librairy可以帮助我创建自定义管道。

这是从数据库中获取CountryCodeCountryName的实际代码

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;
  }

谢谢!

2 个答案:

答案 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);
});