Sunny-117 / js-challenges

✨✨✨ Challenge your JavaScript programming limits step by step

Home Page:https://juejin.cn/column/7244788137410560055

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

求 最接近的值

Sunny-117 opened this issue · comments

const arr = [3, 56, 56, 23, 7, 76, -2, 345, 45, 76, 3];
const num = 37
commented
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);
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));
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];
}
commented
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];
}
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]

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