用reduce方法实现
如果有相同的最小值
a <= b 时会找到最先出现的值
a < b 时会找到最后出现的值
idx 目标值索引
var arrs = [
0.55, 0.75, 1.1, 1.5, 2.2, 2.2, 3, 4, 5.5, 7.5, 11, 15, 18.5, 22, 30, 37, 45,
55, 75, 90, 110,
];
function findDiffMinNum(arr, num) {
let idx = 0;
const min = arr.reduce((prev, current, index) => {
const a = Math.abs(prev - num);
const b = Math.abs(current - num);
return a <= b ? (prev) : ((idx = index), current);
}, 0);
console.log('idx :>> ', idx, arr[idx], arr[idx + 1]);
return min;
}
h = 2.2;
var diffMin = findDiffMinNum(arrs, h);
console.log('diffMin :>> ', diffMin);
其它实现 js数字和数组匹配获取最接近的值
该博客介绍了如何利用JavaScript的reduce方法来查找数组中与给定目标值最接近的元素。示例代码展示了当有相同最小差值时,如何找到最先出现或最后出现的值,并返回其索引和值。此外,还提供了一个用于找出数组中与给定数字最接近值的函数findDiffMinNum。
1153

被折叠的 条评论
为什么被折叠?



