1

I have this data array retrieved from the database with Axios, I want to return the sum of a field based on some conditions

I already used map() to grab the data from my backend :

// getData.js

return (
  <ul>
    {attendance.map(({ _id, name, male }) => {

      return (
        <div key={_id}>
          <br />
          <hr />
          <li>{name}</li>
          {/* the condition is to render only male that are  >= 2 */}
          <li>{male >= 2 ? male : 0}</li>
        </div>
      )
    })}
  </ul>
)

//output

Joshua Jaccob
2

Fabio Rio
2

Lancelot Abe
2

Bello
0

Becca Andrew
0

I want to sum the total male that fit the condition, also render only those that fit the condition

1
  • What's your question? Does your code not work? It's difficult to tell with this code what the issue is because you haven't provided an example of the data you're using. Commented Sep 6, 2019 at 7:39

3 Answers 3

2

You could push all attendances with your condition into a list, then length of the list will be total number.

The last, just render the list.


// get all attendances with male >= 2
const list = attendance.filter(({ male }) => {
  return male >= 2;
});

return (
  <div>
    <h3>Total attendances with male >= 2: {list.length}</h3>
    <ul>
//pass in name and _id
      {list.map(({ name,_id }) => {
        return (
          <div key={_id}>
            <br />
            <hr />
            <li>{name}</li>
          </div>
        )
      })}
    </ul>
  </div>
)
Sign up to request clarification or add additional context in comments.

Comments

0
attendance.filter((male)=>male>=2)
.map((_id,ind,male)=>{
return (
 //male.length will give you the sum of total male that fill the condition

)
}

Array.prototype.filter gives u an array of results which only passes the condition in this case the age>=2

Comments

0

Use .filter function to filter the array using the condition then use map to render like below.

return (
  <ul>
    {attendance
      .filter(({ male }) => male >=2 )
      .map(({ _id, name, male }) => {
        return (
          <div key={_id}>
            <br />
            <hr />
            <li>{name}</li>
            <li>{male}</li>
          </div>
        )
      })
    }
  </ul>
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.