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.
Advertisement
Answer
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
.