Use reduce() method to create a function for finding the smallest interval in an Array using JavaScript.
Example get the smallest difference value from an array in JavaScript
HTML example code.
<!DOCTYPE html>
<html>
<body>
<script>
<!DOCTYPE html>
<html>
<body>
<script>
function getMin(data) {
return data.reduce(function(r, e, i) {
let absR = Math.abs(r), absE = Math.abs(e);
if (absR > absE || i == 0 || (absR == absE && e > r)) r = e
return r
})
}
// Test
console.log(getMin([1, 2, 4, 5, 7, 9]))
console.log(getMin([1.5, -1, 5, 5.5, -4]))
console.log(getMin([1, -1, 5, 5.5, -4]))
console.log(getMin([8, 2, 4, 8, 16]))
</script>
</body>
</html>
Output:
![Find the smallest interval in Array JavaScript](https://i0.wp.com/tutorial.eyehunts.com/wp-content/uploads/2021/07/Find-the-smallest-interval-in-Array-JavaScript.jpg?resize=257%2C205&ssl=1)
Do comment if you have any doubt or suggestions on this Js Array code.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version