2

I'm fairly new to Angular so maybe I'm just searching for the wrong thing, but I can't seem to find an easy answer to this anywhere.

Let's say I have an array of objects:

[
  {Label: "UDP 128B Flood", ...},
  {Label: "UDP 512B Flood", ...},
  {Label: "UPD 1514B Flood",...},
  {Label: "HTTP Excessive GET",...} 
]

This is array is being displayed as the options in a dropdown:

<option *ngFor="let profile of Profiles" [value]="profile.Label">{{profile.Label}}</option>

I want to sort these objects to make sure they show up in alphanumeric order.

iamcootis
  • 2,203
  • 3
  • 18
  • 22

3 Answers3

3

Use the array.prototype.sort function

let sorted = [
  {Label: "UDP 128B Flood"},
  {Label: "UDP 512B Flood"},
  {Label: "UDP 1514B Flood"},
  {Label: "HTTP Excessive GET"} 
].sort((a, b) => a.Label.localeCompare(b.Label));

console.log(sorted);
user184994
  • 17,791
  • 1
  • 46
  • 52
0

Javascript : natural sort of alphanumerical strings

Found the answer from this thread.

profiles.sort((as, bs) => {
var a: any, b: any, a1: number, b1: number, i= 0, n: number , L,
    rx=/(\.\d+)|(\d+(\.\d+)?)|([^\d.]+)|(\.\D+)|(\.$)/g;
if(as.Label=== bs.Label) return 0;
a= as.Label.toLowerCase().match(rx);
b= bs.Label.toLowerCase().match(rx);
L= a.length;
while(i<L){
    if(!b[i]) return 1;
    a1= a[i],
        b1= b[i++];
    if(a1!== b1){
        n= a1-b1;
        if(!isNaN(n)) return n;
        return a1>b1? 1:-1;
    }
}
return b[i]? -1:0;

});

iamcootis
  • 2,203
  • 3
  • 18
  • 22
0

Try this, hope this would help.

var array=[
  {Label: "UDP 128B Flood", ...},
  {Label: "UDP 512B Flood", ...},
  {Label: "UPD 1514B Flood",...},
  {Label: "HTTP Excessive GET",...} 
]
array.sort(this.sortArray);
sortArray(){ if(b.Label.toString().toLowerCase() <a.Label.toString().toLowerCase()) { return -1; }
if(b.Label.toString().toLowerCase() >a.Label.toString().toLowerCase()) { return 1; } }
HUSSAIN
  • 600
  • 4
  • 18
Syed Kashif
  • 420
  • 6
  • 13