我需要按属性 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
我认为不可能的方法。也许有一些包装函数。
如何实现?
最佳答案
您可以使用乘数
并根据order
变量将其设置为1
或-1
。然后将其乘以 compareFunction
内的现有表达式(这里我假设 price
的类型为 number
)
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/