javascript find nearest element
// Find the number from `arr` which is closest to `n`
const closest = (arr, n) => arr.reduce((prev, curr) => Math.abs(curr - n) < Math.abs(prev - n) ? curr : prev);
// Or
const closest = (arr, n) => arr.sort((a, b) => Math.abs(a - n) - Math.abs(b - n))[0];
// Example
closest([29, 87, 8, 78, 97, 20, 75, 33, 24, 17], 50); // 33
Also in JavaScript:
- selected option attribute jquery
- radio button onchange jquery
- javascript sleep function
- location.reload sweetalert
- acces store from vue console javascript
- can you get reinfected with the coronavirus
- javascript remove css link
- how to downgrade node version
- codepen
- javascript add event listener to all input
- kendo grid get all selected items
- "SyntaxError: Unexpected token o in JSON at position 1
- parse json to dart model
- check if all elements in array match a condition javascript
- make select option selected javascript
- react three fiber
- discord command js
- ajax call
- javascript string includes
- js draggable
- javascript json stringify indented
- object methods in javascript
- javascript detect if object is date
- localstorage.getitem()