将静态元素设置为下拉列表中的最后一个元素?

时间:2019-05-09 11:34:43

标签: angular

我有用于排序的代码。在此数据中,我有一个名为“其他”的元素,并且希望该元素始终保留为最后一个。

     getallIndustries() {
    this.customerService.getAppIndustry()
      .subscribe(
        (data: any) => {
          this.industries$ = this.sortData(data);
        },
        error => this.errMsg = error,
      );
  }

  sortData(value) {
    return value.sort((a, b) => {
      const itemA = a.name.toUpperCase();
      const itemB = b.name.toUpperCase();
      return itemA.localeCompare(itemB);
    });
  }

我尝试这样的事情:

    if (a.name === 'OTHER') {
  return 1;
}
if (a.name > b.name) {
  return 1;
}
if (a.name < b.name) {
  return -1;
}
return 0;

}

这是我的数组列表:0: "Agriculture and Mining" 1: "Business Services" 2: "Computer and Electronics" 3: "Consumer Services" 4: "Education" 5: "Energy and Utilities" 6: "Financial Services" 7: "Government" 8: "Health, Pharmaceuticals, and Biotech" 9: "Manufacturing" 10: "Media and Entertainment" 11: "Non-profit" 12: "Other" 13: "Real Estate and Construction" 14: "Retail" 15: "Software and Internet" 16: "Telecommunications" 17: "Transportation and Storage" 18: "Travel Recreation and Leisure" 19: "Wholesale and Distribution"

但是这在某种程度上是行不通的,因为我在其他地方使用了相同的功能并且效果很好,请问有人可以帮我吗。

我什至直接尝试对父母:

      getAppIndustry(): Observable<IIndustry[]> {
    return this.http.get<IIndustry[]>(this.getIndustry_Url)
      .pipe(
        map((res: IIndustry[]) => {
          console.log('ress eshte '+ res);
          return res.sort((a, b) => this.compareCategories(a, b));
        }),
        catchError(this.handleError),
      );
  }

  private compareCategories(a: IIndustry, b: IIndustry) {
    if (a.name === 'Other') {
      return 1;
    }
    if (a.name > b.name) {
      return 1;
    }
    if (a.name < b.name) {
      return -1;
    }
    return 0;
  }

2 个答案:

答案 0 :(得分:1)

从数组中删除元素,对数组进行排序,然后将其放回末尾:

const data = [
  { id: 1, name: 'Bob' },
  { id: 2, name: 'Christie' },
  { id: 3, name: 'Zachary' },
  { id: 4, name: 'Miguel' },
  { id: 5, name: 'Henri' },
  { id: 6, name: 'Cassidy' },
  { id: -1, name: 'Other' }
];

const staticEl = data.find(el => el.name === 'Other'); // Or use ID to find

const sorted = [...data
  .filter(el => el !== staticEl)
  .sort((a, b) => a.name.localeCompare(b.name)), staticEl];

console.log(sorted.map(el => el.name));

答案 1 :(得分:1)

以下排序功能将名称为“其他”的项目保留在最后位置:

sortData(value) {
  return value.sort((a, b) => {
    const itemA = a.name.toUpperCase();
    const itemB = b.name.toUpperCase();
    if (itemA === "OTHER") {
      return 1;
    } else if (itemB === "OTHER") {
      return -1;
    } else {
      return itemA.localeCompare(itemB);
    }
  });
}

有关演示,请参见this stackblitz