0

I have an array of objects, and I'd like to find the closest number to a specific key value. I've seen other answers that show how to do it for an array full of numbers, but I can't figure out the syntax for doing the same thing to an array of objects. Here's my (simplified) code:

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);

Let's say I'm looking for the closest value of x when my goal is number 2.2. How would I go about writing this? Any help would be much appreciated!

Anthony
  • 11
  • 2
  • So you just use `curr.x` and `prev.x` in your `reduce`. – Tim Roberts Apr 01 '23 at 03:34
  • When I try that I get `SyntaxError: Unexpected token '.'`. Thanks anyways though! – Anthony Apr 01 '23 at 03:40
  • How simplified is the code? Will the `x`s always be monotonically increasing in the array? Will they always be *linearly* increasing with `t`? Separately, you should post your try with the SyntaxError ([edit] it in). – Ry- Apr 01 '23 at 03:51
  • `curr` and `prev` are objects, you need to get the `x` value from them: `return (Math.abs(curr.x - goal) < Math.abs(prev.x - goal) ? curr : prev)` – Hao Wu Apr 01 '23 at 03:52

0 Answers0