Ask Your Question
3

In JavaScript, how can we find the number in an array that is closest in value to a specific object key?

asked 2023-03-13 11:00:00 +0000

djk gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-05-24 10:00:00 +0000

nofretete gravatar image

One way to find the number in an array that is closest in value to a specific object key in JavaScript is:

  1. Create an array of numbers and specify the target key value.

    const arr = [5, 10, 15, 20, 25];
    const target = 18;
    
  2. Use the map() method to create a new array with the absolute difference between each element in the original array and the target value.

    const diffArr = arr.map(num => Math.abs(num - target));
    
  3. Use the Math.min() method to find the minimum value in the diffArr.

    const minDiff = Math.min(...diffArr);
    
  4. Use the indexOf() method to find the index of the minimum value in the diffArr.

    const index = diffArr.indexOf(minDiff);
    
  5. Return the element in the original array at the same index.

    const closestNum = arr[index];
    
  6. The closestNum variable now holds the number in the array that is closest in value to the specified object key.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-03-13 11:00:00 +0000

Seen: 10 times

Last updated: May 24 '22