how do i find the object element in an array that has the nearest number?

var target = 13;
var arr = [{num: 1}, {num: 10}, {num: 20}];


const find = (arr, target) => {
  return arr.reduce((acc, { num }, index) => {
    return (Math.abs(num - target) < Math.abs(acc.num - target) ? {num, index} : acc)}, {num: 0, index: 0});
}
        
console.log(find(arr, target));

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top