Issue
I have a JSON response that has teamId from 1 to 43
[{"teamId":"1"},{"teamId":"2"},{"teamId":"3"},{"teamId":"4"},{"teamId":"5"},{"teamId":"6"},{"teamId":"7"},{"teamId":"8"},{"teamId":"9"},{"teamId":"10"},{"teamId":"11"},{"teamId":"12"},{"teamId":"13"},{"teamId":"14"},{"teamId":"15"},{"teamId":"16"},{"teamId":"17"},{"teamId":"18"},{"teamId":"19"},{"teamId":"20"},{"teamId":"21"},{"teamId":"22"},{"teamId":"23"},{"teamId":"24"},{"teamId":"25"},{"teamId":"26"},{"teamId":"27"},{"teamId":"28"},{"teamId":"29"},{"teamId":"30"},{"teamId":"31"},{"teamId":"32"},{"teamId":"33"},{"teamId":"34"},{"teamId":"35"},{"teamId":"36"},{"teamId":"37"},{"teamId":"38"},{"teamId":"39"},{"teamId":"40"},{"teamId":"41"},{"teamId":"42"},{"teamId":"43"}]
from the api the numbers are well sorted, but when I try to display them on angular 10 , they end up mixed up, have tried to sort the data using on sort method, but no luck,
what I have so far, component.ts
onSort({column, direction}: SortEvent) {
this.sort = {column, direction};
if (direction === '') {
this.teams = this.teams;
} else {
this.teams = [...this.teams].sort((a, b) => {
const res = compare(a[column], b[column]);
return direction === 'asc' ? res : -res;
});
}
}
in my component.html
<tr>
<th [sortable]="'teamId'" (sort)="onSort($event)"> Team Code
</tr>
what could I be doing wrong?
Solution
You can create a compare function which you should then pass to the array.sort()
function, where you compare the values of the object to each other.
array = [
{ teamId: '1' },
{ teamId: '5' },
{ teamId: '6' },
{ teamId: '7' },
{ teamId: '34' },
{ teamId: '35' },
{ teamId: '36' },
{ teamId: '37' },
{ teamId: '38' }
]
sortArray(array: { teamId: string; }[]) {
array.sort(this.compare);
}
compare( a, b ) {
return a.teamId - b.teamId
}
I created a stackblitz where you can test the functionality: Stackblitz
For more insight on how the Array.sort method works see here: Array.prototype.sort()
Answered By - JB17
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.