blue-success - 9 months ago 40

Javascript Question

I need to write a function that takes two inputs, 'target' (integer) and 'values' (a list of integers), and find which number in 'values' is closest to 'target'. I came up with the following:

`var targetNum = 0;`

var valuesArr = [2, 4, 6, 8, 10];

function closestToTarget(target, values) {

var currVal = values[0];

var diff = Math.abs(target - currVal);

for (var i = 0; i < values.length; i++) {

var currDiff = Math.abs(target - values[i]);

if (currDiff < diff) {

diff = currDiff;

currVal = values[i];

}

}

return currVal;

}

alert(closestToTarget(targetNum, valuesArr));

The function works, but I'm unable to return the smaller value in the case of a tie. The best that I could think of was the following which did not work:

`function closestToTarget(target, values) {`

var currVal = values[0];

var diff = Math.abs(target - currVal);

for (var i = 0; i < values.length; i++) {

var currDiff = Math.abs(target - values[i]);

if (currDiff < diff) {

diff = currDiff;

currVal = values[i];

}

else if (currDiff == diff) {

return Math.min[currVal, values[i]];

}

else {

return currVal[i - 1];

}

}

return currVal;

}

In the case of a tie, how do I return the smaller number in JavaScript?

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

Your idea should work, but you could also use your first function but with the addition of something that checks for a lower tie at the end:

```
function closestToTarget(target, values) {
var currVal = values[0];
var diff = Math.abs(target - currVal);
for (var i = 0; i < values.length; i++) {
var currDiff = Math.abs(target - values[i]);
if (currDiff < diff) {
diff = currDiff;
currVal = values[i];
}
}
// We found the closest but now check if there's a smaller tie
if (currVal > target && values.indexOf(target - diff) > -1 ) {
return target - diff;
}
else {
// if not just return what we originally found
return currVal;
}
}
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**