Say I have an array of objects:
const arr = [ {num:3,numTwo:1}, {num:5,numTwo:3}, {num:7,numTwo:9}, {num:7,numTwo:3}, {num:8,numTwo:4} ] const goal = 7
I have this code that properly finds the closest number when ONLY accounting for num
:
const closest = arr.reduce(function (prev, curr) { return Math.abs(curr.num - goal) < Math.abs(prev.num - goal) ? curr : prev; });
It returns {num:7,numTwo:9}
(because first instance), but I want numTwo to come into play where it returns the object with the lowest numTwo
if in the case goal
matches with multiple matching num
‘s, so in this case it should return {num:7,numTwo:3}
Advertisement
Answer
Make your expression a subtraction and use ||
to involve the comparison of numTwo
when that subtraction is 0:
const arr = [{num:3,numTwo:1},{num:5,numTwo:3},{num:7,numTwo:9},{num:7,numTwo:3},{num:8,numTwo:4}]; const goal = 7; const closest = arr.reduce(function (prev, curr) { return (Math.abs(curr.num - goal) - Math.abs(prev.num - goal) || curr.numTwo - prev.numTwo) < 0 ? curr : prev; }); console.log(closest);