How to custom sort JSON array in Typescript or Angular
11,568
Just sort the array using Array#sort
method.
// reference for sort order priority
const ref = {
15: 0,
6: 1,
1: 2,
11: 3,
9: 4,
2: 5,
3: 6
};
let data = [{
"title": "DEASDFS",
"Id": 11
},
{
"title": "AASDBSC",
"Id": 2
},
{
"title": "JDADKL",
"Id": 6
},
{
"title": "MDASDNO",
"Id": 3
},
{
"title": "GHFASDI",
"Id": 15
},
{
"title": "HASDFAI",
"Id": 1
},
{
"title": "ASDHFI",
"Id": 9
},
];
console.log(
data.sort((a, b) => ref[a.Id] - ref[b.Id])
)
Or implement custom pipe for sorting : Angular 2 OrderBy Pipe
Related videos on Youtube
Author by
Mr world wide
I'm enthusiastic and experienced Fullstack web developer
Updated on June 04, 2022Comments
-
Mr world wide almost 2 years
How to sort JSON array in Angular? The array:
{"title":"DEASDFS","Id":11}, {"title":"AASDBSC","Id":2}, {"title":"JDADKL","Id":6}, {"title":"MDASDNO","Id":3}, {"title":"GHFASDI","Id":15}, {"title":"HASDFAI","Id":1}, {"title":"ASDHFI","Id":9},
I want the order of the Id's like this:
15,6,1,11,9,2,3
<div *ngFor="let field of fieldsData;let i=index;"> <div class="form-inline assigned_text-box" [ngSwitch]="field.Id"> <div class="col-md-2" *ngSwitchCase="15"> <label>One</label> </div> <div class="col-md-2" *ngSwitchCase="6"> <label>Two</label> </div> <div class="col-md-2" *ngSwitchCase="1"> <label>Three</label> </div> <div class="col-md-2" *ngSwitchCase="11"> <label>Four</label> </div> <div class="col-md-2" *ngSwitchCase="9"> <label>Five</label> </div> <div class="col-md-2" *ngSwitchCase="2"> <label>Six</label> </div> <div class="col-md-2" *ngSwitchCase="3"> <label>Seven</label> </div> </div> </div>
But when I use
ngSwitch
conditio,n which ever coming first that is printing so it coming like as present in JSON 11,2,6,3,15,1,9But I want this order 15,6,1,11,9,2,3. How can I achieve this custom sort array?
-
Aravind over 6 yearsin which sort logic you will place it?
-
Zahidur Rahman over 6 yearsCan u customely sort your array before implementation of view.
-
smnbbrv over 6 yearsArray.prototype.sort?
-
Mr world wide over 6 yearsAny method is fine, is it possible to sort in
ngFor div
..?
-
-
Mr world wide over 6 yearsSimple and clean solution thanks, is it possible do from view side in Angular..?
-
Pranav C Balan over 6 years@Mrworldwide : you can create a custom pipe for sorting