Show Output
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Sort Numeric Array Correctly in JavaScript</title> </head> <body> <script> var numbers = [1, 5, 12, 3, 7, 15, 9]; // Sorting the numbers array simply using the sort method numbers.sort(); // Sorts numbers array document.write(numbers + "<hr>"); // Outputs: 1,12,15,3,5,7,9 /* Sorting the numbers array numerically in ascending order using the sort method and a compare function */ numbers.sort(function(a, b){ return a - b; }); document.write(numbers); // Outputs: 1,3,5,7,9,12,15 </script> </body> </html>