Emil Andersson logotype
Written by Emil Andersson on
January 25th, 2023 in Tutorials

How to sort arrays in JavaScript

JavaScript provides several ways to sort arrays. The most commonly used method is the built-in sort() function. This function sorts the elements of an array in place and returns the sorted array. By default, the sort() function sorts elements alphabetically. However, it can also be used to sort elements numerically by passing in a comparison function.

To sort an array of numbers in ascending order, you can use the following code:

let numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
numbers.sort(function(a, b) {
    return a - b;
});
console.log(numbers);

This will output [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9].

To sort an array of strings in descending order, you can use the following code:

let words = ["dog", "cat", "zebra", "ape", "lion"];
words.sort(function(a, b) {
    return b.localeCompare(a);
});
console.log(words);

This will output ["zebra", "lion", "dog", "cat", "ape"].

Another way to sort an array in JavaScript is to use the Array.prototype.slice().sort() method. This method creates a copy of the original array, sorts the copy, and leaves the original array unchanged.

let words = ["dog", "cat", "zebra", "ape", "lion"];
let sortedWords = words.slice().sort();
console.log(sortedWords);
console.log(words);

This will output ["ape", "cat", "dog", "lion", "zebra"] and ["dog", "cat", "zebra", "ape", "lion"]

In case you want to sort array based on object property, you can use sort and pass comparator function which compares objects based on the given property.

let arr = [{name:'John',age:25},{name:'Mike',age:35},{name:'Nancy',age:40}];
arr.sort((a, b) => (a.name > b.name) ? 1 : -1)

In conclusion, JavaScript provides multiple ways to sort arrays, including the built-in sort() function, Array.prototype.slice().sort() method and passing comparator function to sort array of objects based on property. It's important to choose the right method based on your needs and requirements.

Tags

  • javascript
  • sort
  • array
  • slice
  • compare