Как отсортировать массив в реагировать - PullRequest
0 голосов
/ 10 апреля 2019

Я бы хотел отсортировать массив в ReactionJS

Я пытался использовать метод javascript sort (), но он не сортируется. Я уже реализовал фильтр, который работает, но не смог заставить работать сортировку!



  constructor(props) {
    super(props);
    this.state = {
      persons: [],
      search: '',
      key: null,
      direction: {
        name: 'asc',
      }

    };
    this.sortBy = this.sortBy.bind(this);
  }

  componentDidMount(){
    axios.get(`https://jsonplaceholder.typicode.com/users`)
    .then(res => {
      console.log(res);
      this.setState({ 
        persons: res.data      
      });
    }); 
  }

  sortBy(e,key){
    console.log("keeo  "+key + "  - e  "+e.target.value); 

    this.setState({
      key: key
      persons: this.state.persons.sort( 
        (person) => { return 
        this.state.direction[key] === 'asc'
        ? 
        parseFloat(a[key]) - parseFloat(b[key])
        : parseFloat(b[key]) - parseFloat(a[key])
    })
      .direction: {
        [key]: this.state.direction[key] === 'asc' ? 'desc' : 'asc'
      }
    })
  }

  // inside render 

  <button onClick = {(e,name) => this.sortBy(e,'name')}>Name</button>
<button onClick = {(e,amount) => this.sortBy(e,'amount')}>amount</button>

<button onClick = {(e,city) => this.sortBy(e,'city')}>city</button>



Я хочу иметь возможность сортировки по person.name, person.amount, person.city

Спасибо за вашу помощь

1 Ответ

0 голосов
/ 10 апреля 2019

Вы можете использовать фильтр sortBy из библиотеки "lodash":

let sortedArrPersons = _.sortBy(persons, ['name', 'amount', 'city']);

Например:

var users = [
  { 'user': 'fred',   'age': 48 },
  { 'user': 'barney', 'age': 36 },
  { 'user': 'fred',   'age': 40 },
  { 'user': 'barney', 'age': 34 }
];
_.sortBy(users, ['user', 'age']);
// => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]]

Для более подробной информации посетите: https://lodash.com/docs/4.17.11#sortBy

...