EN
JavaScript - sort array
14
points
In this article, we would like to show you how to sort arrays in JavaScript.
1. Sorting array alphabetically
In this example, to sort the array
in alphabetical order we use Array
sort
(Array.prototype.sort
) method.
// ONLINE-RUNNER:browser;
var array = ['C', 'A', 'B'];
array.sort();
console.log(array);
2. Sorting array in ascending order with compare function
In this example, numbers are sorted from smallest to biggest with compare function.
// ONLINE-RUNNER:browser;
var array = [5, 2, 3, 1, 4];
array.sort(function(a, b) {
return a - b;
});
console.log(array);
3. Sorting array in descending order
In this example, to sort the array in descending order we swap the subtraction components (negative and subtractive) in the compare function.
// ONLINE-RUNNER:browser;
var array = [5, 2, 3, 1, 4];
array.sort(function(a, b) {
return b - a;
});
console.log(array);
4. Sorting array in descending order with reverse method example
In this example numbers are sorted from biggest to smallest - in this case, the reverse
function has been used.
Note:
To sort array in descending order, we recommend to use the previous solution.
// ONLINE-RUNNER:browser;
var array = [5, 2, 3, 1, 4];
array.sort(function(a, b) {
return a - b;
}).reverse();
console.log(array);