You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript中如何查找数组对象指定key的最接近数值?

查找对象数组中指定字段最接近目标值的对象

我有一个对象数组,想要查找其中某个指定key的数值与目标值最接近的对象。我已经知道纯数字数组的实现方法,但不清楚对象数组的写法。以下是我的简化代码:

let x = 0;
let y = 1.524;
const array = [{t:0, x:x, y:y}];
const tI = 0.0014;

for (let i = 0; i < 25; i++){
    array.push({t:array[i].t + tI, x:array[i].x + 0.1, y:array[i].y + 10});
    console.log(array[i]);
}

// Get the closest number in array
goal = 2.2;
var closest = array.reduce(function(prev, curr) {
  return (Math.abs(curr - goal) < Math.abs(prev - goal) ? curr : prev);
});
console.log(closest);

修改方案

要查找x字段数值最接近目标值2.2的对象,只需调整reduce回调里的差值计算逻辑——因为数组元素是对象,必须提取对应的x属性来计算与目标值的距离:

let x = 0;
let y = 1.524;
const array = [{t:0, x:x, y:y}];
const tI = 0.0014;

for (let i = 0; i < 25; i++){
    array.push({t:array[i].t + tI, x:array[i].x + 0.1, y:array[i].y + 10});
}

const goal = 2.2;
// 修改reduce回调,提取对象的x属性计算差值
const closest = array.reduce(function(prev, curr) {
  const prevDiff = Math.abs(prev.x - goal);
  const currDiff = Math.abs(curr.x - goal);
  return currDiff < prevDiff ? curr : prev;
});
console.log(closest);

关键说明

  • 用prev.x和curr.x替代原代码中的prev和curr,这样计算的是对象x字段与目标值的差值绝对值
  • 最终返回的是完整对象,而非单独的数值,符合需求

内容的提问来源于stack exchange,提问作者User

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 14:58:20