[英]How to sort an array by the closest number
I'm trying to sort an array by the closest item to a specific number我正在尝试按最接近特定数字的项目对数组进行排序
The following solution doesn't work in all cases, for no reason以下解决方案并非在所有情况下都有效,无缘无故
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 works with this example: 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);
In both cases you are returning a positive number.在这两种情况下,您都返回一个正数。 That is to say, in both cases you are returning >0
.也就是说,在这两种情况下,您都返回>0
。 Which means your code is really doing:这意味着您的代码确实在做:
if (Math.abs(b.price - price) > Math.abs(a.price - price)) {
sort b before a
} else {
sort b before a
}
Basically your if
statement is not doing anything.基本上你的if
语句没有做任何事情。
What you really want is:你真正想要的是:
if (Math.abs(b.price - price) > Math.abs(a.price - price)) {
return 1
} else {
return -1
}
or或者
if (Math.abs(b.price - price) > Math.abs(a.price - price)) {
return -1
} else {
return 1
}
depending on weather you want to sort ascending or descending.根据您想要升序或降序排序的天气。
Better yet you really should be doing:更好的是,您确实应该这样做:
return Math.abs(b.price - price) - Math.abs(a.price - price)
or或者
return Math.abs(a.price - price) - Math.abs(b.price - price)
I believe this works.我相信这行得通。
let array = [{"price":"6850000"},{"price":"6692301"},{"price":"6880000"},{"price":"6735100"},{"price":"6708900"},{"price":"7000000"}]
var price = 6692300;
const closestArray = array.sort((a, b) => {
const distOne = a.price - price;
const distTwo = b.price - price;
return Math.abs(distOne) - Math.abs(distTwo);
});
console.log(closestArray);
What you were doing was that you were returning a price but that price was always greater than 0 which is supposed to return a number greater than 0 only if the second one, or b, should come first.您所做的是返回一个价格,但该价格始终大于 0,只有当第二个或 b 应该首先出现时,才应该返回一个大于 0 的数字。
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 1;
} else if (Math.abs(b.price - price) > Math.abs(a.price - price)) {
return -1;
}
return 0; // because they are equal in value and should have equal ordering
})
console.log(closestArray);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.