Q:

How to Sort an Array of Integers Correctly in JavaScript

0

How to Sort an Array of Integers Correctly in JavaScript

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Use the sort() Method

If you simply try to sort a numeric array using the sort() method it will not work, because the sort() method sorts the array elements alphabetically. But, you can still sort an array of integers correctly through utilizing a compare function, as shown in the following example:

<script>
var numbers = [1, 5, 12, 3, 7, 15, 9];
    
// Sorting the numbers array simply using the sort method
numbers.sort(); // Sorts numbers array
alert(numbers); // 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;
});
alert(numbers); // Outputs: 1,3,5,7,9,12,15
</script>

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Return Multiple Values from a Function in J... >>
<< How to Check for an Empty String in JavaScript...