Access / Order an array dynamically in JavaScript / React [closed]

-1

I'm trying to do an array sorting, it's already working.

This code:

search = async() => {
    const response = await api.post('/client/find', { "filter": this.state.filterSelected, "input": this.state.textSearch });

  // ordenar de acordo com o select
  var comparador = this.state.filterSelected.toLowerCase();
  this.setState({ docs: response.data.sort((a, b) => {
    if (a.name < b.name) return -1; // sort string ascending
    if (a.name > b.name) return 1;
    return 0; // default return value (no sorting)
  })});

  this.setState({docs: response.data});
}

It takes an array of the API (in a MongoDB database) and shows it on the screen, in an array ordered by name.

The problem is that I wanted to do this according to a select of the selected page, the comparator variable, already returns the name, but it would not work puts the commaster, because it went behind comparator, not name, even though passing the name value in the comparator variable Would you like to pass name in the value of the comparator variable and use it in ifs? if (a partition) return -1;

    
asked by anonymous 30.12.2018 / 23:42

1 answer

0

If you want to delete conditionals to sort according to the selected filter, all you need to do is do it here:

// 1. obter o nome do filtro onde o nome é SEMPRE igual a uma propriedade do elementos elementos que vc quer filtrar

// removi o lowercase pq esse valor TEM que ter ser associado ao campo q vc quer filtrar
const key = this.state.filterSelected 

// 2. Agora o filtro

this.setState({ docs: response.data.sort((a, b) => {
  if (a[key] < b[key]) return -1; // sort string ascending
  if (a[key] > b[key]) return 1;
  return 0; // default return value (no sorting)
})});

See that key is used to get a value of a or b dynamically.

I really do not know if this is what you want because your question is not clear enough but from what you commented, I believe it to be that.

Be sure to improve your question so that in the future other people can be helped okay?

    
07.01.2019 / 05:08