首页 > 解决方案 > 排序数组升序和降序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);

}

上升是有效的,但下降是无效的。

标签: reactjssorting

解决方案


您传入的函数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;
  })

推荐阅读