How to sum of array of objects with numbers in react


This is an short tutorial on how to get sum of numbers in React applicaiton

Let’s consider the array of objects as given below

 [{
      firstName: "John",
      lastName: "Erwin",
      email: "john@gmail.com",
      salary:5000
      },
      {
    firstName: "Ram",
      lastName: "Kumar",
      email: "john@gmail.com",
      salary:5000
      }
]

Array contain objects with different employee properties.

Let’s see an example how to print array of objects into html table , and also calculate sum of object numeric values and display it in React component.

  • Created a React Component NumberSum
  • Created an array of objects and store array in react state
  • In Render method construct html table with table thead, tbody and tfoot.
  • Iterate an array objects using array map method and construct an string with all tr and td of rows and columns.
  • Sum of numbers using array reduce method which has accumulator initialized to 0 initially and add currentItem salary into accumulator and finally return sum of salary
  • Finally using javascript expressions embed those values inside html table tags
import React, { Component } from 'react';
import { render } from 'react-dom';

export default class NumberSum extends Component {
    constructor(props) {
    super(props);
    this.state = {
      data:  [{
      firstName: "John",
      lastName: "Erwin",
      email: "john@gmail.com",
      salary:5000},
      {firstName: "Ram",
      lastName: "Kumar",
      email: "john@gmail.com",
      salary:5000
      }]}
    }
  render() {
  const tableBody=this.state.data.map((item =>
  <tr key={item.firstname}><td >{item.firstName}</td><td >{item.lastName}</td><td >{item.email}</td><td>{item.salary}</td>
  </tr>
  ));
  const total=(this.state.data.reduce((total,currentItem) =>  total = total + currentItem.salary , 0 ));
    return (
      <table>
      <thead><tr><th>first</th>
      <th>last</th>
      <th>Email</th>
      <th>Salary</th>
    </tr>
  </thead>
  <tbody>{tableBody}
  </tbody>
  <tfoot><tr>
      Total: 
      {total}
    </tr>  
  </tfoot>
  </table>)
  }
}

Output React calculate sum of numbers and display array of objects into html table

Conclusion

This is an short tutorial with example in react

  • How to display an array of objects into html table
  • Get sum of array of object number properties
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.