Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

求 最接近的值 #109

Open
Sunny-117 opened this issue Nov 3, 2022 · 6 comments
Open

求 最接近的值 #109

Sunny-117 opened this issue Nov 3, 2022 · 6 comments

Comments

@Sunny-117
Copy link
Owner

const arr = [3, 56, 56, 23, 7, 76, -2, 345, 45, 76, 3];
const num = 37
@bearki99
Copy link

const arr = [3, 56, 56, 23, 7, 76, -2, 345, 45, 76, 3];
const num = 37;
function getClose(num, arr){
    let res = arr[0];
    for(let i = 1; i < arr.length; i++){
        if(Math.abs(arr[i] - num) < Math.abs(res - num)){
            res = arr[i];
        }
    }
    return res;
}
const res = getClose(num, arr);
console.log(res);

@Tylermeek
Copy link

Tylermeek commented Feb 21, 2023

function getClose(target, arr) {
  let cloest = [Number.MAX_SAFE_INTEGER, 0];
  arr.forEach((element) => {
    let temp = Math.abs(element - target);
    if (temp < cloest[0]) {
      cloest[0] = temp;
      cloest[1] = element;
    }
  });
  return cloest[1];
}
console.log(getClose(num, arr));

@veneno-o
Copy link
Contributor

function main(arr, num){
    const dif = arr.map(item => Math.abs(item - num));
    let minIndex = 0;
    for(let i = 1; i < arr.length; ++i){
        dif[i] < dif[minIndex] && (minIndex = i);
    }
    return arr[minIndex];
}

@fencer-yd
Copy link

fencer-yd commented Jun 1, 2023

function getClose(target, arr) {
   const dif = arr.map(item => Math.abs(item - target));
  const min = Math.min(...dif);
  const index = dif.findIndex(i => i === min);
  return arr[index];
}

@kangkang123269
Copy link

kangkang123269 commented Sep 11, 2023

function findClosest(arr,num){
    var closestArr = arr.map(function(val){
        return Math.abs(num-val);
    });
    
    var minDiff = Math.min(...closestArr);

    var indexArr=[];
    
    closestArr.forEach(function(val,i){
        if(val === minDiff)
            indexArr.push(i);
     });

     if(indexArr.length >1)
         return indexArr.map(i=>arr[i]);
     
     else 
         return arr[closestArr.indexOf(minDiff)];
}

let arr1= [3 ,56 ,56 ,23 ,7 ,76 ,-2 ,345 ,45 ,76];
let num1=37;
console.log(findClosest(arr1,num1)); // 输出:45

let arr2=[1, 2, 3];
let num2=2;
console.log(findClosest(arr2,num2)); // 输出:2

let arr3=[1, 3];
let num3=2;
console.log(findClosest(arr3,num3)); // 输出: [1, 3]

@gswysy
Copy link

gswysy commented Feb 28, 2024

function a(arr, num) {
return arr.reduce((a, b) => {
return Math.abs(num - a) > Math.abs(num - b) ? b : a
})
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

7 participants