Home > other >  How to find min , max on array and how to change color text for min green color and max red color us
How to find min , max on array and how to change color text for min green color and max red color us

Time:10-14

I have the JSON like below but I have a lot of data:

items: [ { itemId: "22222", category: 'A', total: 100 }, { itemId: "666666", category: 'A', total: 80 }, { itemId: "555", category: 'B', total: 50 } .... ... { itemId: "555", category: 'B', total: 2 } ]

I create on .scss

   &.is-green {
      color: green;
    }
    &.is-red {
      color: red;
    }

I want to use it something like that:

<div *ngFor="let item of items;> 
    <div>{{item.category}}</div>
    <div 
      [ngClass]="{
        'is-green': item.total ,
        'is-red':item.total
         }"
       >
       {{item.total}}</div>
    </div>

From this data I want to find min total and change color to green. I want to find also max total and change color red.

Please, have you any idea how to make this?

CodePudding user response:

So, this question has two parts, right ? The first one is sorting and the second one is changing the first and last items green and red.

For Sorting, you can use this

items = items.sort((fstItem, secItem)=> fstItem.total > secItem.total ? 1 :
fstItem.total < secItem.total -1 : 0 );

for second thing, you can use in html with first and last index from *ngFor

<div *ngFor="let item of items; first as isFirstItem; last as isLastItem;"> 
  <div>{{item.category}}</div>
  <div [ngClass]="{'is-green': isFirstItem,
                   'is-red': isLastItem
                    }">
   {{item.total}}
  </div>
</div>
  • Related