admin管理员组文章数量:1401241
I'd like to find an algorithm to order by closest value. I think an example would clarify what i'm saying :
Let say we have an array like this :
var arr = [10,45,69,72,80];
and var num = 73;
What i would like is a function that returns this array like this.
function orderByClosest(arr, num){
//enter code here
return arr; //and arr = [72,69,80,45,10]
}
Hope i'm clear enough.
Thanks.
I'd like to find an algorithm to order by closest value. I think an example would clarify what i'm saying :
Let say we have an array like this :
var arr = [10,45,69,72,80];
and var num = 73;
What i would like is a function that returns this array like this.
function orderByClosest(arr, num){
//enter code here
return arr; //and arr = [72,69,80,45,10]
}
Hope i'm clear enough.
Thanks.
Share Improve this question asked Jun 6, 2016 at 10:41 Matt WalterspielerMatt Walterspieler 2,1912 gold badges23 silver badges37 bronze badges 2-
2
What should happen if
var num = 40
– Rayon Commented Jun 6, 2016 at 10:42 -
For
var num = 40
, it would output[45,69,10,72,80]
– Matt Walterspieler Commented Jun 6, 2016 at 11:19
2 Answers
Reset to default 10You can use Array#sort
with Math.abs()
.
arr.sort((a, b) => Math.abs(a - num) - Math.abs(b - num));
Using ES5 Syntax for older browsers
arr.sort(function(a, b) {
return Math.abs(a - num) - Math.abs(b - num);
});
To consider negative numbers too, don't use Math.abs()
.
var arr = [10, 45, 69, 72, 80];
var num = 73;
var result = arr.sort((a, b) => Math.abs(a - num) - Math.abs(b - num));;
console.log(result);
For greater amount of data, I suggest to use Sorting with map.
function orderByClosest(list, num) {
// temporary array holds objects with position and sort-value
var mapped = list.map(function (el, i) {
return { index: i, value: Math.abs(el - num) };
});
// sorting the mapped array containing the reduced values
mapped.sort(function (a, b) {
return a.value - b.value;
});
// return the resulting order
return mapped.map(function (el) {
return list[el.index];
});
}
console.log(orderByClosest([72, 69, 80, 45, 10], 73));
console.log(orderByClosest([72, 69, 80, 45, 10], 40));
本文标签: javascriptOrder an array by closest valuesStack Overflow
版权声明:本文标题:javascript - Order an array by closest values - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744200482a2594938.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论