Index of closest element in JavaScript



Suppose we have an array like this βˆ’

const arr = [2, 42, 82, 122, 162, 202, 242, 282, 322, 362];

We are required to write a JavaScript function that takes in one such array and a number, say n.

The function should return the index of item from the array which is closest to the number n.

Therefore, let’s write the code for this function βˆ’

Example

The code for this will be βˆ’

const arr = [2, 42, 82, 122, 162, 202, 242, 282, 322, 362];
const closestIndex = (num, arr) => {
   let curr = arr[0], diff = Math.abs(num - curr);
   let index = 0;
   for (let val = 0; val < arr.length; val++) {
      let newdiff = Math.abs(num - arr[val]);
      if (newdiff < diff) {
         diff = newdiff;
         curr = arr[val];
         index = val;
      };
   };
   return index;
};
console.log(closestIndex(150, arr));

Output

The output in the console will be βˆ’

4
Updated on: 2020-10-24T11:51:40+05:30

196 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements