admin管理员组

文章数量:1401241

I'd like to find an algorithm to order by closest value. I think an example would clarify what i'm saying :

Let say we have an array like this : var arr = [10,45,69,72,80]; and var num = 73;

What i would like is a function that returns this array like this.

function orderByClosest(arr, num){
  //enter code here
  return arr; //and arr = [72,69,80,45,10]
}

Hope i'm clear enough.

Thanks.

I'd like to find an algorithm to order by closest value. I think an example would clarify what i'm saying :

Let say we have an array like this : var arr = [10,45,69,72,80]; and var num = 73;

What i would like is a function that returns this array like this.

function orderByClosest(arr, num){
  //enter code here
  return arr; //and arr = [72,69,80,45,10]
}

Hope i'm clear enough.

Thanks.

Share Improve this question asked Jun 6, 2016 at 10:41 Matt WalterspielerMatt Walterspieler 2,1912 gold badges23 silver badges37 bronze badges 2
  • 2 What should happen if var num = 40 – Rayon Commented Jun 6, 2016 at 10:42
  • For var num = 40, it would output [45,69,10,72,80] – Matt Walterspieler Commented Jun 6, 2016 at 11:19
Add a ment  | 

2 Answers 2

Reset to default 10

You can use Array#sort with Math.abs().

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

Using ES5 Syntax for older browsers

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

To consider negative numbers too, don't use 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);

For greater amount of data, I suggest to use Sorting with map.

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

本文标签: javascriptOrder an array by closest valuesStack Overflow