Skip to content
Advertisement

angular array loop using ngFor get array count and display the value

I showed data using below angular functions

availableLockers = [
    {
      "lockerCode": "L01",
      "allocStatus": "alloc"
    },
    {
      "lockerCode": "L02",
      "allocStatus": "un-alloc"
    },
    {
      "lockerCode": "L03",
      "allocStatus": "un-alloc"
    },
    {
      "lockerCode": "L04",
      "allocStatus": "temp-alloc"
    }, {
      "lockerCode": "L05",
      "allocStatus": "alloc"
},]

I am using bellow html

<div *ngFor="let locker of availableLockers let i=index;">{{locker.lockerCode}} </div>

The above code is working well. currently I need do display count of each status. Ex: how many lockers with “alloc” status, how many lockers with “temp-alloc” status.

Advertisement

Answer

You can try with filter(),

let availableLockers = [
  {
    lockerCode: 'L01',
    allocStatus: 'alloc'
  },
  {
    lockerCode: 'L02',
    allocStatus: 'un-alloc'
  },
  {
    lockerCode: 'L03',
    allocStatus: 'un-alloc'
  },
  {
    lockerCode: 'L04',
    allocStatus: 'temp-alloc'
  },
  {
    lockerCode: 'L05',
    allocStatus: 'alloc'
  }
];

function checkStatus(status) {
  let data = availableLockers.filter(locker => locker.allocStatus === status);
  return data.length;
}

console.log(checkStatus('alloc'));
console.log(checkStatus('un-alloc'));
console.log(checkStatus('temp-alloc'));
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement