Sort state object in React

I am trying to create a way to click on my table header ("First Name", "Last Name" etc) and have the data sort accordingly.

        <Container>
        <table className="table table-hover">
        <thead>
            <tr>
            <th scope="col" >Image</th>
            <th scope="col" value="firstName" onClick={this.sortFirstName}>First Name</th>
            <th scope="col" value="lastName">Last Lame</th>
            <th scope="col" value="email">Email</th>
            <th scope="col" value="phoneNumber">Phone Number</th>
            <th scope="col" value="city">City</th>
            <th scope="col" value="SSN">SSN</th>
            </tr>
        </thead>
        <tbody>
        {this.state.filteredEmployeeData.map(ee => (
          <EmployeeData
            id={ee.login.uuid}
            key={ee.login.uuid}
            img={ee.picture.thumbnail}
            firstName={ee.name.first}
            lastName={ee.name.last}
            email={ee.email}
            phone={ee.cell}
            city={ee.location.city}
            ssn={ee.id.value}
          />
        ))}
        </tbody>
        </table>
        </Container>

You can see on the First Name that I’m trying to create an onClick function that would allow me to sort the data according to the first name.

Here’s an example of how I’m trying to create the function:

  sortEmail(){
    console.log('SORTING!!!!')
    const {filteredEmployeeData} = this.state
    const sorted = filteredEmployeeData.sort((a, b) => {
          if (a.email < b.email){
            return -1
        } else if (a.email > b.email){
            return 1
        } else {
          return 0
        }
    })
    console.log('Sorted List: ', sorted)
    this.setState({filteredEmployeeData: sorted})
}

Any help here is appreciated!

82 thoughts on “Sort state object in React”

Leave a Comment