2

I have array of Objects and I add my data to HTML Table. Now I need to sort my data by version. How can I do something like that in React?

  render() {
    return (
      <div>
        <div>
          <Label> We got {this.state.count} elements in our database. </Label>
        </div>
        <div>
          <Table hover striped bordered responsive size="sm" >
            <thead>
              <tr>
                <th>VERSION</th>
                <th>DATE</th>
                <th>UUID</th>
              </tr>
            </thead>
            <tbody>
              {this.state.results.map(result =>
                <tr key={result.fileId}>
                  <td>{result.VERSION}</td>
                  <td>{result.ORIGIN}</td>
                  <td>{result.UUID}</td>
                </tr>
              )}
            </tbody>
          </Table>
        </div>
      </div>
    );
  }
}

Maybe I can use some js script, but tell me how to use it, I'm new with ReactJS. My version for is 0.26.8 for example.

3 Answers 3

3

I would use lodash's sortBy() function here:

https://lodash.com/docs/4.17.4#sortBy

const sorted = _.sortBy(this.state.results, 'VERSION')

Then map over sorted instead of the this.state.results

Sign up to request clarification or add additional context in comments.

Comments

2

Simply make sure this.state.results is sorted correctly before rendering.


The simplest approach would likely be similar to the following:

  {this.state.results.sort((a, b) => a.VERSION - b.VERSION).map(result =>
    <tr key={result.fileId}>
      <td>{result.VERSION}</td>
      <td>{result.ORIGIN}</td>
      <td>{result.UUID}</td>
    </tr>
  )}

Edit: Since you stated that the version is not a numeric value, but rather a semantic versioning string, your sort function needs to be a bit more complex. I suggest you have a look at this SO question, or use one of the many available libraries covering that use case.

1 Comment

My version looks like: 0.22.6, not only one number. I forgot to add it to description. Already updated, sorry.
1
const sorted = results.sort((x,y) => {
    return parseInt(x.VERSION) - parseInt(y.VERSION);
});

sorts in Ascending order

1 Comment

My version looks like: 0.22.6, not only one number. I forgot to add it to description. Already updated, sorry.

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.