我需要通过属性price来订购对象数组。

现在,我可以执行以下操作:

function orderByPriceASC(a,b) {
    return(
      a.price < b.price ? -1
      : a.price > b.price ? 1
        : 0
    );
  }

  function orderByPriceDESC(a,b) {
    return(
      a.price < b.price ? 1
      : a.price > b.price ? -1
        : 0
    );
  }

  function sortByPrice(order) {
    setProductList((prevState) => {
      const aux = Array.from(prevState);
      order === 'asc' ? aux.sort(orderByPriceASC) : aux.sort(orderByPriceDESC);
      return aux;
    });
  }


但是,有没有办法构造这种结构,这样我就可以获得一个适用于ASC和DESC订单的比较函数?

就像是:

function orderByPrice(a,b,order) {
    return(
      a.price < b.price ?
        order === 'asc' ? -1 : 1
      : a.price > b.price ? 1
        order === 'asc' ? 1 : -1
        : 0
    );
  }


问题是我必须将多余的参数发送到Array.sort方法,我认为这是不可能的。也许有一些包装功能。

如何实现呢?

最佳答案

您可以使用multiplier并根据1变量将其设置为-1order。然后将其乘以compareFunction中的现有表达式(此处假设pricenumber类型)



let arr = [{ price: 2 },{ price: 1 },{ price: 3 }]

function sort(array, order) {
  const multiplier = order === "asc" ? 1 : -1;
  return array.sort((a, b) => multiplier * (a.price - b.price))
}

console.log(sort(arr, "asc"))
console.log(sort(arr, "desc"))

关于javascript - 获取单个比较函数以使用Array.sort()对ASC和DESC进行排序?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56365461/

10-12 12:39
查看更多