-3

I have array of objects. Here i need to sort value while binding.

simple.ts

this.data =  
      [
         {
            name : 'C1A5'
         },
         {
            name : 'C1A1'
         },
         {
            name : 'C1A2'
         },
         {
            name : 'C1A4'
         },
         {
            name : 'C1A3'
         },
         {
            name : 'C1A7'
         },
         {
            name : 'C1A6'
         }
      ]

simple.html

 <div class="" *ngFor="let d of data">
      {{d.name}}
</div>

Here how can I sort to get below result in UI:

 'C1A1'
    'C1A2'
    'C1A3'
    'C1A4'
    'C1A5'
    'C1A6'
    'C1A7'

Thanks in advance.

Rajesh Bunny
  • 329
  • 1
  • 2
  • 7
  • 1
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort – JB Nizet Mar 18 '19 at 07:24
  • 1
    Possible duplicate of [Sort array of objects by string property value](https://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value) – zmag Mar 18 '19 at 07:27

2 Answers2

1

If you want a one-liner solution, one of the ways to sort it would be to make use of localeCompare() on your comparison function.

this.data.sort((a, b) => a['name'].localeCompare(b['name']));

Also, please tag your question with the appropriate tags. This is a general JavaScript question, hence you should tag it with 'JavaScript' instead.

wentjun
  • 40,384
  • 10
  • 95
  • 107
0

you can use .sort() for sorting array like javascript style in angular

this.data.sort(function (a, b) {
  return a.name - b.name;
});
Faisal
  • 584
  • 3
  • 11
  • 33