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.

Alex
  • 1,221
  • 2
  • 26
  • 42

3 Answers3

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

Max Millington
  • 4,378
  • 4
  • 27
  • 34
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.

TimoStaudinger
  • 41,396
  • 16
  • 88
  • 94
  • My version looks like: `0.22.6`, not only one number. I forgot to add it to description. Already updated, sorry. – Alex Jul 25 '17 at 17:25
1
const sorted = results.sort((x,y) => {
    return parseInt(x.VERSION) - parseInt(y.VERSION);
});

sorts in Ascending order

Anthony
  • 6,422
  • 2
  • 17
  • 34
  • My version looks like: 0.22.6, not only one number. I forgot to add it to description. Already updated, sorry. – Alex Jul 25 '17 at 17:28