对数组排序由值最接近1 [英] Sorting an array by which value is closest to 1

查看:139
本文介绍了对数组排序由值最接近1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要进行排序的值的数组。

I need to sort an array of values.

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

通过该值最接近 1 ,这会(在上面的例子中)导致:

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.

也许有人能赐教。

推荐答案

刚刚从1检查他们的距离。

Just check their distance from 1.

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

只是为了阐述,它计算两个数字1的距离,即对

Just to elaborate, 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阵列中的

  • 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.

由于在意见中的要求,下面的适应会给preference将值低于1。

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));
});

这篇关于对数组排序由值最接近1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆