JavaScript

How to sort an array of numbers in JavaScript

If you try to sort an array of numbers using the sort() method, it will not work, because the sort() method sorts the elements of the array alphabetically, as shown in the following example:

var nbrs = [1, 4, 13, 3, 8, 16, 9];
 
// We've just used the sort() method
nbrs.sort(); 
console.log(nbrs);

Output:

1,13,16,3,4,8,9
 
However, you can still sort an array of integers correctly by using a comparison function, as shown in the following example:

var nbrs = [1, 4, 13, 3, 8, 16, 9];
 
/* Sorting the array in ascending order using the sort() method and compare function */
nbrs.sort(function(a, b){
    return a - b;
});
console.log(nbrs);

Output:

1,3,4,8,9,13,16
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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