首页 > 解决方案 > 如何在数组中打印数字,同时将其与 Js 中的预定义值进行比较

问题描述

我有一个数字数组:

array = [20, 44, 55, 66, 24, 38, 500];
key = 25.5;

我想基本上将数组中的每个值与键进行比较,并打印从与该键最接近的数字开始的数字。例如:在上面的例子中,我希望 o/p 看起来像:

newarray =[24,20,38, 44,66,500] // 24 is closest to 25.5, 20 is second closest to 25.5, 38 is thrid closest to 25.5, etc...

代码:

var len = array.length;

array.forEach(function(i){
  if(i === key) {
    return i;
}

})

我不确定如何根据数组中最接近的数字打印这些数字。有什么想法吗?

标签: javascript

解决方案


与其使用 for 循环,不如使用 Javascript 的Array.prototype.sort()函数。

const array = [20, 44, 55, 66, 24, 38, 500];
const key = 25.5;

// Create a sorting helper
sortByClosestToKey = (a, b) => {
  // Calculate how far away each number is from the key
  const aDiff = Math.abs(a - key);
  const bDiff = Math.abs(b - key);
  return (aDiff < bDiff) ? -1 : (aDiff > bDiff) ? 1 : a < b;
}

const sorted = array.sort(sortByClosestToKey);

document.querySelector('#answer').innerText = sorted.toString();
<div id="answer"></div>


推荐阅读