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!