javascript - 如何在数组中打印数字,同时将其与 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;
}
})
我不确定如何根据数组中最接近的数字打印这些数字。有什么想法吗?
解决方案
与其使用 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>
推荐阅读
- android - 如何修复颤振中的尺寸错误?
- javascript - 语音识别 API。Speechend 事件和 Speechstart 无法正常工作。特别是speechend
- confluence - 组织在一个部门下运行的所有项目所需的建议
- google-sheets - 如何应用基于其他 Google Work Book 值的条件格式?
- angular - RecordRTC 录制取消
- android - 是否可以使用 onselectChanged 在颤振中删除数据表的特定行?如果是,请提供示例代码
- apache-spark - Spark - 如果数据框中的日期有多个时间戳可用,则按时间戳降序排列
- azure - 能否强制 Azure 存储防火墙允许没有 VNET 的 Azure 应用服务?
- android - 如何在 Android 中正确使用 ViewModel?
- c# - 如何在roslyn分析器中获取一个类的所有接口