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.
You 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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With