How To Simulate A Max Method On Arrays In JavaScript

admin_img Posted By Bajarangi soft , Posted On 09-10-2020

In Java script we can find the largest number (in a list of numbers) using the Math.max() method. so today we discuss how to max methods in java script

How To Simulate A Max Method On Arrays In JavaScript

Example(1)

<h2 id="demo"></h2>

<script>
    document.getElementById("demo").innerHTML = Math.max(1,2,3);
</script>

Since JavaScript arrays do not have a max() method, you can apply the Math.max() method instead.

Example(2)
<h2 id="demo1"></h2>
<script>
    document.getElementById("demo1").innerHTML = Math.max.apply(null, [1,2,3,4]);
</script>
 

The first argument (null) does not matter. It is not used in this example.

These examples will give the same result:
Example(3)

<h2 id="demo2"></h2>
<script>
    document.getElementById("demo2").innerHTML = Math.max.apply(Math, [1,2,3,4,5]);
</script>

Example(4)
<h2 id="demo3"></h2>

<script>
    document.getElementById("demo3").innerHTML = Math.max.apply(" ", [1,2,3,10]);
</script>

Example(5)
<h2 id="demo4"></h2>

<script>
    document.getElementById("demo4").innerHTML = Math.max.apply(0, [1,2,3,15]);
</script>

Complete Code For Simulating A Max Method On Arrays In JavaScript
<!DOCTYPE html>
<html>
<head>
    <title>How To Simulate A Max Method On Arrays In JavaScript</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
    <br>
    <div class="text-center">
        <h1 id="color" style="color: tomato">How To Simulate A Max Method On Arrays In JavaScript</h1>
    </div>

    <div class="well">
        <h2 id="demo"></h2>
        <h2 id="demo1"></h2>
        <h2 id="demo2"></h2>
        <h2 id="demo3"></h2>
        <h2 id="demo4"></h2>

        <script>
            document.getElementById("demo").innerHTML = Math.max(1,2,3);
            document.getElementById("demo1").innerHTML = Math.max.apply(null, [1,2,3,4]);
            document.getElementById("demo2").innerHTML = Math.max.apply(Math, [1,2,3,4,5]);
            document.getElementById("demo3").innerHTML = Math.max.apply(" ", [1,2,3,10]);
            document.getElementById("demo4").innerHTML = Math.max.apply(0, [1,2,3,15]);
        </script>
    </div>
</div>
</body>
</html>

 

Related Post