Sort an array whose 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];

the value of which is closest to 1, which (in the above example) will result in:

[0.98, 1.12, 0.76, 1.36, 0.3, 1.9];

I know using a special sort function.

arr.sort(function(a, b){
    return b - a;
});

I can control how it works sort(), but I don’t understand how I could create this user-defined function so that it works in the desired way.

Maybe someone can enlighten me.

+4
source share
3 answers

Just check their distance from 1.

arr.sort(function(a, b){
    return Math.abs(1-a) - Math.abs(1-b);
});

To clarify, it calculates the distance of two numbers from 1, i.e. for

  • a=-10 b=4, 11 3 . , 4 -10 .
  • a=-1 b=4, 2 3, , -1 4 .

, 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));
});
+16

, , 1, , , , 1, , , , :

var arr = [1.02, 0.3, 0.76, 0.98, 1.12, 1.36, 1.9, 1.24];

// Unbiased
arr.sort(function(a, b){
    return Math.abs(1-a) - Math.abs(1-b);
});

console.log('unbiased: ' + arr); // unbiased: 1.02,0.98,1.12,0.76,1.24,1.36,0.3,1.9

var arr = [1.02, 0.3, 0.76, 0.98, 1.12, 1.36, 1.9, 1.24];

// Biased so numbers less than 1 sort higher than those greater than 1
// where their difference from 1 is equal
arr.sort(function(a, b) {
  var da = 1 - a;
  var db = 1 - b;

  da -= da < 0? 1e-14 : 0;
  db -= db < 0? 1e-14 : 0;

  return Math.abs(da) - Math.abs(db);
});

console.log('biased: ' + arr); // biased: 0.98,1.02,1.12,0.76,1.24,1.36,0.3,1.9
0

@batscream

arr = arr.sort((a, b) => {
    return Math.abs(1-a) - Math.abs(1-b);
});

var arr = [0.3, 0.76, 0.98, 1.12, 1.36, 1.9];
arr = arr.sort((a, b) => {
    return Math.abs(1-a) - Math.abs(1-b);
});
console.log(arr);
Hide result

: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

0

All Articles