0

I am displaying an array (CatFilterPro) in a Flatlist, when a button is pressed I want to sort it by high price to low and when the other button is pressed do the reverse, the below code is working fine for the first press, but it could not sort it again after the first sort.

lowpricefilter() {

    this.fc= this.state.recentPro2
    this.fc.sort(function(a, b) {
        return Number(a.pro_price) - Number(b.pro_price);
    })
    this.setState({
        CatFilterPro: this.fc,
        modalVisible: false

    })   
}


highpricefilter() {
    this.fc= this.state.recentPro2
    this.fc.sort(function(a, b) {
        return Number(b.pro_price) - Number(a.pro_price);
    })
    this.setState({
        CatFilterPro: this.fc,
        modalVisible: false
    })   
}

2 Answers 2

1
sortByDescending = (a, b) => {
  if(a === b) return 0;
  if(a > b) return -1;
  return 1;
};

sortByAscending = (a, b) => a - b;

sort = sortFunction => {
  const { recentPro2: fc } = this.state;
  return fc.sort(sortFunction);
}

lowpricefilter = () => {
  const sortedAscending = this.sort(this.sortByAscending));
  this.setState({
    CatFilterPro: sortedAscending,
    modalVisible: false
  });
}

highpricefilter = () => {
  const sortedDescending = this.sort(this.sortByDescending));
  this.setState({
    CatFilterPro: sortedDescending,
    modalVisible: false
  });
}
Sign up to request clarification or add additional context in comments.

4 Comments

still it doesn't do the sort after the ascending or descending was done, it just sort for the first press
I've just updated my answer, I accidentally added 2 lowpricefilter. I've changed this now. If you still get the prob, let me know.
I did edited and try it, I don't think my problem is in the sorting part, its in the rendering, i console log the array and its quite sorted for asc and des but it doesn't display the items sorted in the flatlist just for the first sort it does display.
Try adding extraData={this.state} to your FlatList.
0

You have to bind your functions in your constructor

this.highpricefilter = this.highpricefilter.bind(this);
this.lowpricefilter = this.lowpricefilter.bind(this);

1 Comment

I have bind the functions, its sorting fine for the first time i press the button but when i want to sort again, it doesn't.

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.