Home > Back-end >  How to show total count of elements based on two conditions in react js?
How to show total count of elements based on two conditions in react js?

Time:05-19

I am trying to show total count of participants based on two conditions: have "Nume": "4S110" and "Nume": "Contabilitate" from INDICATORI array and Cursuri array.

to show them as

const cont = popular.reduce((total, participant) => total   participant.Cursuri
  .filter(curs => curs.Nume === "Contabilitate") && participant.INDICATORI
  .filter(indicator => indicator.Nume === "4S110").length,0)

output is : 0, it should be 1


api is:

```
"rows": [
   {
     "id": "15f806ec-79cf-498f-8a4d-8bc8fdf8c43e",
     "Nume": "negrea",
     "Prenume": "ioana",
     "Varsta": 40,
     "createdAt": "2022-04-27T13:17:05.000Z",
     "updatedAt": "2022-04-27T13:17:05.000Z",
     "deletedAt": null,
     "INDICATORI": [
       {
         "id": "068170b3-7995-41df-8fac-4f2bc577e2c6",
         "Nume": "4S110",
         "importHash": null,
         
       }
     ],
     "Cursuri": [{
         "id": "068170b3-7995-41df-8fac-4f2bc577e2c6",
         "Nume": "Contabilitate",
         "importHash": null,
         ]
   },

CodePudding user response:

The .filter() function returns an array so you need to add .length. Math.min() can help in case you want to count such person only once (must have an entry in both items).

let popular = JSON.parse(`[
   {
     "id": "15f806ec-79cf-498f-8a4d-8bc8fdf8c43e",
     "Nume": "negrea",
     "Prenume": "ioana",
     "Varsta": 40,
     "createdAt": "2022-04-27T13:17:05.000Z",
     "updatedAt": "2022-04-27T13:17:05.000Z",
     "deletedAt": null,
     "INDICATORI": [
       {
         "id": "068170b3-7995-41df-8fac-4f2bc577e2c6",
         "Nume": "4S110",
         "importHash": null         
       }
     ],
     "Cursuri": [{
         "id": "068170b3-7995-41df-8fac-4f2bc577e2c6",
         "Nume": "Contabilitate",
         "importHash": null
         }]
   }]`);
   

 
 const count = popular.reduce((total, participant) => total   Math.min(participant.Cursuri
  .filter(indicator => indicator.Nume === "Contabilitate").length, participant.INDICATORI
  .filter(indicator => indicator.Nume === "4S110").length), 0)

 console.log(count);

  • Related