I have a list of commodity items where i have to sort all IDM items in alphabetical order and below that DM items in alphabetical order, rite now my code displays like WRONG: order:but i want to display like Correct first IDM and next DM
**WRONG:**
DM-Air
DM-BELL
DM-CEL
IDM-AIR
IDM-BELL
IDM-CELL
**CORRECT**
IDM-AIR
IDM-BELL
IDM-CELL
DM-Air
DM-BELL
DM-CEL
my code is
this.supplier.getCommoditiesFamilyList().subscribe(
(data: any) => {
this.commoditiesFamilyList = data;
this.commoditiesFamilyList.sort(this.commoditySortByName);
},
this.supplier.getCommoditiesFamilyList(id).subscribe(
data => {
this.commoditiesFamilyList = data;
this.commoditiesFamilyList.sort(this.commoditySortByName);
},
[![this.subscriberLevelId = id;
this.supplier.getCommoditiesFamilyList(id).subscribe(
data => {
this.commoditiesFamilyList = data;
this.commoditiesFamilyList.sort(this.commoditySortByName);
},][1]][1]
public commoditySortByName(a, b) {
if (a.name < b.name) {
return -1;
}
if (a.name > b.name) {
return 1;
}
return 0;
}
}
You should just switch 1
and -1
in commoditySortByName
function
I've written this for you, not knowing how you want to sort the part before the separation. My guess is reversed order?
this.commoditiesFamilyList = this.commoditiesFamilyList
.map(item => {
var splitted: string[] = item.split('-');
return {'pre': splitted[0], 'post': splitted[1]};
})
.sort(this.commoditySortByPre)
.sort(this.commoditySortByPost)
.map(item => item.pre + '-' + item.post);
public commoditySortByPre(a, b) {
if (a.pre < b.pre) {
return 1;
}
if (a.pre > b.pre) {
return -1;
}
return 0;
}
public commoditySortByPost(a, b) {
if (a.name < b.name) {
return -1;
}
if (a.name > b.name) {
return 1;
}
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.