Cant find the solution when sorting an array in JavaScript

Hi guys I can't figure out why this code doesn't work. Could you please shed some light on? I create an array and try to sort it and then display the content on the page. if I remove the sorting part it works, otherwise it doesn't.

<button type="button" onclick="myFunction()">Click Me -- -- - -- - !</button>
<p id="NULL"> asdf </p>
<p id="demoto+0">This is gonna be changed </p>
<p id="demoto+1">This is gonna be changed </p>
<p id="demoto+2">This is gonna be changed </p>
<p id="demoto+3">This is gonna be changed </p>
<p id="demoto+4">This is gonna be changed </p>
<p id="demoto+5">This is gonna be changed </p>

<div id="demoto+6"> to be changed </div>
<script>

function myFunction() { 
    var arr = [1,23, 32, 94, 280, 294];
    document.getElementById("NULL").innerHMTL = arr[0];
    int n = 6;
    for(int i=0; i<n-1; ++i)
    {
        int index = i;
        for(int j=i+1; j<n; ++j)
        {
            if(arr[index] < arr[j])
            {
                index = j;  
            }

        }
        if(i != index)
        {
            int temp = arr[j];
            arr[j] = arr[index];
            arr[index] = temp;
        }

    }

        document.getElementById("demoto+0").innerHTML = arr[0];
        document.getElementById("demoto+1").innerHTML = arr[1];
        document.getElementById("demoto+2").innerHTML = arr[2];
        document.getElementById("demoto+3").innerHTML = arr[3];
        document.getElementById("demoto+4").innerHTML = arr[4];
        document.getElementById("demoto+5").innerHTML = arr[5];

}
</script>

Answers:

Answer

How about :

arr.sort(function(a, b) {
    return a - b;
});

to do the sort() ?

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.