按最接近的值对数组进行排序

4
我希望能找到一个算法来按最接近的值排序。我想通过一个例子来阐明我的意思:
假设我们有这样一个数组: var arr = [10,45,69,72,80];var num = 73; 我想要的是一个函数,它返回这个数组像这样排序。
function orderByClosest(arr, num){
  //enter code here
  return arr; //and arr = [72,69,80,45,10]
}

希望您能明确表达。感谢您。

2
如果 var num = 40,应该发生什么? - Rayon
对于 var num = 40,它将输出 [45,69,10,72,80] - Matt Walterspieler
2个回答

9

您可以使用Array#sortMath.abs()

arr.sort((a, b) => Math.abs(a - num) - Math.abs(b - num));

使用ES5语法兼容老版本浏览器

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

要考虑负数,不要使用 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);


1

对于更大量的数据,我建议使用地图排序

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接