How to custom sort JSON array in Typescript or Angular

Mr world wide picture Mr world wide · Jan 30, 2018 · Viewed 9.4k times · Source

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,9

But I want this order 15,6,1,11,9,2,3. How can I achieve this custom sort array?

Answer

Pranav C Balan picture Pranav C Balan · Jan 30, 2018

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