js-challenges icon indicating copy to clipboard operation
js-challenges copied to clipboard

求 最接近的值

Open Sunny-117 opened this issue 3 years ago • 7 comments

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

Sunny-117 avatar Nov 03 '22 08:11 Sunny-117

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

bearki99 avatar Feb 13 '23 02:02 bearki99

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

Tylermeek avatar Feb 21 '23 12:02 Tylermeek

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

veneno-o avatar Mar 10 '23 19:03 veneno-o

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

fencer-yd avatar Jun 01 '23 10:06 fencer-yd

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]

kangkang123269 avatar Sep 11 '23 08:09 kangkang123269

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

Aurora-GSW avatar Feb 28 '24 11:02 Aurora-GSW