admin管理员组

文章数量:1431720

I'm trying to reverse this sort on click using ReactJS:

        if (this.state.Prz==3) {
        this.props.files.sort(function(a,b){
            return a.lastModified < b.lastModified ? 1 : -1;
        });
    }

I tried many tricks searching on Google but I'm still stuck.

I'm trying to reverse this sort on click using ReactJS:

        if (this.state.Prz==3) {
        this.props.files.sort(function(a,b){
            return a.lastModified < b.lastModified ? 1 : -1;
        });
    }

I tried many tricks searching on Google but I'm still stuck.

Share Improve this question asked Aug 24, 2017 at 10:11 MeowMeowMeowMeow 931 gold badge2 silver badges8 bronze badges 3
  • Seems okay to me. – Haroldo_OK Commented Aug 24, 2017 at 10:14
  • 1 How should the sort order be determined? Does it e from the state, or the props, or what? It seems like you just need to put a condition inside the sort function. – Tom Fenech Commented Aug 24, 2017 at 10:19
  • sort is determined by the props. I add condition it's work better, but seems my lasModified is wrong but it help a lot, thanks – MeowMeow Commented Aug 24, 2017 at 11:07
Add a ment  | 

3 Answers 3

Reset to default 3

You can change the direction of sort (since you seem to be sorting by Date) by swapping 1 and -1:

this.props.files.sort(function(a,b){
    return a.lastModified < b.lastModified ? -1 : 1;
});

Or you can reverse the array, assuming it was sorted before doing that (concat() is for making a copy of the array, keeping things "immutable"):

this.props.files.concat().reverse();

You can reverse an array simply by calling reverse

this.props.files.reverse()

Beware though that this will mutate the original array.

Here finally how I did. I add a condition.

    if (this.state.activePrz==3) {
        this.props.files.sort(function(a,b){
            var asc = a.lastModified < b.lastModified;
            var desc = a.lastModified > b.lastModified;
            if(asc == true){
                return asc;
            }else{
                return desc;
            }
        })
    }

And it works.

I couldn't :

this.props.files.reverse();

or

this.props.files.concat().reverse();

The error message was :

Cannot read property 'files' of undefined

Many thanks for your help.

本文标签: javascriptHow reverse sort on reactStack Overflow