One way to find the number in an array that is closest in value to a specific object key in JavaScript is:
Create an array of numbers and specify the target key value.
const arr = [5, 10, 15, 20, 25];
const target = 18;
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));
Use the Math.min()
method to find the minimum value in the diffArr
.
const minDiff = Math.min(...diffArr);
Use the indexOf()
method to find the index of the minimum value in the diffArr
.
const index = diffArr.indexOf(minDiff);
Return the element in the original array at the same index.
const closestNum = arr[index];
The closestNum
variable now holds the number in the array that is closest in value to the specified object key.
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
Asked: 2023-03-13 11:00:00 +0000
Seen: 10 times
Last updated: May 24 '22
What steps can I take to prevent my webpage from slowing down when all parts of a div are displayed?
What is the method to include a loading spinner when a button is clicked?
How can Recursive Quote Embedding for HTML and Javascript be made more advanced?
When printing from WKWebView in Swift, the background is not taken into account.
Is it feasible to utilize a Toggle Button to switch among multiple classes exceeding 2?
What is the process for generating a dynamic subdomain/URL using vue.js?
How can I create a transition on click using CSS without the need for JavaScript?