我正在尝试按与特定数字最接近的项目对数组进行排序
以下解决方案并非在所有情况下都无法正常工作
let array = [{"price":"6850000"},{"price":"6692301"},{"price":"6880000"},{"price":"6735100"},{"price":"6708900"},{"price":"7000000"}]
var price = 6692300
const closestArray = array.sort((a, b) => {
if (Math.abs(b.price - price) > Math.abs(a.price - price)) {
return b.price
} else {
return a.price
}
})
console.log(closestArray)
IT使用此示例:
let array = [401,402,400,478,421,432]
var price = 400
const closestArray = array.sort((a, b) => {
if (Math.abs(b - price) < Math.abs(a - price)) {
return b
}
})
console.log(closestArray);
在两种情况下,您都返回一个正数。也就是说,在两种情况下您都将返回>0
。这意味着您的代码确实在做:
if (Math.abs(b.price - price) > Math.abs(a.price - price)) {
sort b before a
} else {
sort b before a
}
基本上,您的if
声明没有做任何事情。
您真正想要的是:
if (Math.abs(b.price - price) > Math.abs(a.price - price)) {
return 1
} else {
return -1
}
要么
if (Math.abs(b.price - price) > Math.abs(a.price - price)) {
return -1
} else {
return 1
}
根据您要对天气进行升序或降序排序。
更好的是,您确实应该这样做:
return Math.abs(b.price - price) - Math.abs(a.price - price)
要么
return Math.abs(a.price - price) - Math.abs(b.price - price)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句