I need to sort an array of values.
var arr = [0.3, 0.76, 0.98, 1.12, 1.36, 1.9];
by which value is closest to 1
, which would (in the above example) result in:
[0.98, 1.12, 0.76, 1.36, 0.3, 1.9];
I know that by using a custom sort function.
arr.sort(function(a, b){
return b - a;
});
i can take control of how sort()
works, however, i do not understand how i would design that custom function so that it would work in the desired way.
Perhaps someone can enlighten me.
Therefore, to find out the closest number we just return the index of the found minimum in the given array indexArr. indexOf(min) .
PHP - Sort Functions For Arrayssort() - sort arrays in ascending order. rsort() - sort arrays in descending order. asort() - sort associative arrays in ascending order, according to the value. ksort() - sort associative arrays in ascending order, according to the key.
So if the array is like [2, 5, 6, 7, 8, 8, 9] and the target number is 4, then closest element is 5. We can solve this by traversing through the given array and keep track of absolute difference of current element with every element. Finally return the element that has minimum absolute difference.
Just check their distance from 1.
arr.sort(function(a, b){
return Math.abs(1-a) - Math.abs(1-b);
});
Just to elaborate, it calculates the distance of two numbers from 1, i.e. for
a=-10
and b=4
, the distances are 11 and 3 respectively. The
function returns a positive number, so 4 comes before
-10 in the sorted array.a=-1
and b=4,
the distances would be 2 and 3, the function
returns a negative number so -1 comes before 4 in the array.As requested in the comments, the below adaptation would give preference to values below 1.
arr.sort(function(a, b){
if(a<1 && b>=1){return -1;}
if(a>=1 && b<1){return 1;}
return (Math.abs(1-a) - Math.abs(1-b));
});
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