Find the closest index to given value in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in an array of numbers as the first input and a single number as the second input.

The function should find and return the index of the number from the array which is closest to the number specified by second argument.

Example

The code for this will be −

const arr = [0, 65, 131, 196, 259, 323, 388, 453, 517];
const target = 425;
const findClosest = (arr, target) => {
let min;
let chosen = 0;
for (let i in arr) {
min = Math.abs(arr[chosen] − target);
if (Math.abs(arr[i] − target) < min) {
chosen = i;
};
};
return chosen;
};
console.log(findClosest(arr, target));

Output

And the output in the console will be −

7
Published on 23-Nov-2020 11:27:57