Find the smallest interval in Array JavaScript | Example code

Use reduce to create a function for Find smallest interval in Array using JavaScript.

Example get 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

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.