在 JavaScript 中获取最接近对象键值的数字

问题描述 投票:0回答:1

我有一个对象数组,我想找到最接近特定键值的数字。我已经看到 other answers 显示了如何对一个充满数字的数组执行此操作,但我无法弄清楚对对象数组执行相同操作的语法。这是我的(简化的)代码:

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
。我将如何着手写这个?任何帮助将不胜感激!

javascript closest
1个回答
0
投票

要根据目标值在对象数组中找到最接近的 x 值,您可以修改 reduce() 方法中的比较函数来比较每个对象的 x 值与目标值之间的差异,而不是比较每个对象与目标值之间的绝对差值。

这是修改后的代码,用于根据目标值在数组中找到最接近的 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});
    console.log(array[i]);
}

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

在这段修改后的代码中,reduce()方法比较每个对象的x值与目标值的绝对差值,返回x值最接近的对象。 closest 变量将包含具有最接近 x 值的对象,您可以使用 closest.x 访问 x 的值

© www.soinside.com 2019 - 2024. All rights reserved.