reactjs - 排序数组升序和降序reactjs
问题描述
我正在尝试将我的数据从升序排序到降序。这是我的代码:
const onSort = (sortKey) => {
let sortCustomer = [...customers];
sortCustomer.sort(function(a, b){
if(a[sortKey] < b[sortKey]) { return -1; }
if(a[sortKey] > b[sortKey]) { return 1; }
return 0;
})
setcustomers(sortCustomer);
}
上升是有效的,但下降是无效的。
解决方案
您传入的函数sort()
将始终按升序排序,为什么您希望它按降序排序?
.sort(function(a, b){
if(a[sortKey] < b[sortKey]) { return -1; }
if(a[sortKey] > b[sortKey]) { return 1; }
return 0;
})
要按降序对其进行排序,它需要执行以下操作:
.sort(function(a, b){
if(a[sortKey] < b[sortKey]) { return 1; }
if(a[sortKey] > b[sortKey]) { return -1; }
return 0;
})
推荐阅读
- java - Netbeans 9.0/10.0 右键菜单中的“绑定”选项丢失
- amazon-web-services - 使用 AWS Lambdas 无服务器应用程序模型构建多页面无服务器应用程序
- solr - 带有 Spring 数据和基本身份验证的 Solr 7 不起作用
- android - 在将多个图像添加到视频时加快视频处理时间 FFMPEG
- r - R Plotly 时间序列数据显示在日期而不是日期时间
- cakephp - 如何在 cakephp 3.2.7 中使用 saveMany
- angular - 如何以角度将组件函数返回值传递给服务
- python - 如何从多个游标分隔的字典(dictfetchall)中获取值?
- apache-kafka - KSQL 事件合并 - 基于时间戳组合来自单个流的事件
- javascript - Javascript 排序适用于 Firefox 而不是 Chrome