Languages
[Edit]
EN

JavaScript - sort array

14 points
Created by:
Jan-Alfaro
681

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);

 

See also

  1. JavaScript - reverse array

Alternative titles

  1. JavaScript - how to sort array?
  2. JavaScript - sort numbers correctly with Array.sort()
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join