Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find object in array with closest value

I need to get an object in an array by the closest value. Let me explain it by an example:

const data = [
  { age: 52 },
  { age: 53 },
  { age: 54 },
  { age: 60, some: 'data' },
  { age: 66, something: 'else' },
  { age: 72 },
  { age: 78 },
  { age: 84 }
]

I do get the object by using data.find((d)=> d.age === 60). But I do not get an result if the age is 61. In this case I would like to get the same object.

For 64 the next object ({ age: 66, something: 'else' }) should be returned.

As you can see the age value is not linear.

like image 428
user3142695 Avatar asked Jul 15 '26 04:07

user3142695


1 Answers

You can find the difference between all the numbers and whichever one is closest to zero will be your result, to achieve this I have used .reduce() with Math.abs()

const data = [ { age: 52 }, { age: 53 }, { age: 54 }, { age: 60 }, { age: 66 }, { age: 72 }, { age: 78 }, { age: 84 } ];

const getAge = (data, target) => 
  data.reduce((acc, obj) =>
     Math.abs(target - obj.age) < Math.abs(target - acc.age) ? obj : acc
  );
  
console.log(getAge(data, 61)); // {age: 60}
console.log(getAge(data, 50)); // {age: 52}
console.log(getAge(data, -1)); // {age: 52}
console.log(getAge(data, 90)); // {age: 84}

This will also work for more generalized objects that have additional properties other than just age.

like image 138
Nick Parsons Avatar answered Jul 17 '26 17:07

Nick Parsons



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!