Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting an array by which value is closest to 1

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.

like image 401
SquareCat Avatar asked Nov 14 '14 02:11

SquareCat


People also ask

How do you find the closest value to a number in an array?

Therefore, to find out the closest number we just return the index of the found minimum in the given array indexArr. indexOf(min) .

How do you sort an array by value?

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.

How do you find the nearest number in a range?

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.


1 Answers

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.
  • For 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));
});
like image 66
BatScream Avatar answered Nov 04 '22 07:11

BatScream