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
3 Answers
Reset to default 3You 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
版权声明:本文标题:javascript - How reverse sort on react - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745588192a2665038.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论