0

In AngularJS is possible sort an array like this ng-repeat="user in users | orderBy: order" and i need to know how do this in ReactJS, here is an exemple of this in AngularJS

const myApp = angular.module('myApp', [])
myApp.controller('myAppController', ['$scope', $scope => {
  $scope.users = [
    { name: 'Maria', age: 16, color: 'red' },
    { name: 'Mike', age: 18, color: 'black' },
    { name: 'John', age: 23, color: 'green' },
    { name: 'Liza', age: 21, color: 'yellow' }
  ]
  $scope.order = 'name'
  $scope.orderBy = orderBy => $scope.order = orderBy
}])
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<table ng-app="myApp" ng-controller="myAppController">
  <tr>
    <th ng-click="orderBy('name')">Name</th>
    <th ng-click="orderBy('age')">Age</th>
    <th ng-click="orderBy('color')">Color</th>
  </tr>
  <tr ng-repeat="user in users | orderBy: order">
    <td>{{user.name}}</td>
    <td>{{user.age}}</td>
    <td>{{user.color}}</td>
  </tr>
</table>
Philipp Meissner
  • 5,273
  • 5
  • 34
  • 59
Jefter Rocha
  • 387
  • 2
  • 14
  • [Array.prototype.sort()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) has some useful examples for sorting through Object properties. ReactJS doesn't offer such functionality. – Daan Nov 28 '19 at 12:55
  • Does this answer your question? [Sort an array of objects in React and render them](https://stackoverflow.com/questions/43572436/sort-an-array-of-objects-in-react-and-render-them) – Philipp Meissner Nov 28 '19 at 13:02

1 Answers1

2

React.js is a plain javascript.
You should use Array.prototype.sort.
Created stackblitz for you.

import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';

class App extends Component {
  constructor() {
    super();
    this.state = {
      name: 'React',
      order: 'name',
      users: [
        { name: 'Maria', age: 16, color: 'red' },
        { name: 'Mike', age: 18, color: 'black' },
        { name: 'John', age: 23, color: 'green' },
        { name: 'Liza', age: 21, color: 'yellow' }
      ]
    };
    this.sort = this.sort.bind(this); 
    this.setOrder = this.setOrder.bind(this); 
  }

  setOrder(e) {
    const order = e.target.dataset.order;

    this.setState({order});
  }

  sort(a, b) {
    if (!this.state.order) return 0;
    if(a[this.state.order] < b[this.state.order]) { return -1; }
    if(a[this.state.order] > b[this.state.order]) { return 1; }
    return 0;
  }

  render() {
    return (
      <div>
        <button data-order='name' onClick={this.setOrder}>by name</button>
        <button data-order='color' onClick={this.setOrder}>by color</button>
        {this.state.users.sort(this.sort).map(user => <div>name: {user.name}, color: {user.color}</div>)}
      </div>
    );
  }
}

render(<App />, document.getElementById('root'));
nickbullock
  • 6,424
  • 9
  • 27