Skip to content

Find the smallest interval in Array JavaScript | Example code

  • by

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

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

Leave a Reply

Your email address will not be published. Required fields are marked *