sort() Methods in JavaScript

JavaScript1 min read
sort() Methods in JavaScript
javascriptsort methodarray methods

sort() is a built-in method in JavaScript that sorts the elements of an array in place and modifies the original array.

sort() Methods in JavaScript

  • sort() is a built-in method in JavaScript that sorts the elements of an array in place and modifies the original array.
  • By default, it sorts the elements based on their string representation.
  • You can customize the sort order by providing a comparison function as an argument.

Example:

  • Let's create an array names with some names:
let names = ['Alice', 'John', 'Bob', 'Eva', 'Daniel'];

To show all elements in the array, use the forEach() method:

let names = ['Alice', 'John', 'Bob', 'Eva', 'Daniel']; names.forEach(item => { document.write(item + "<br>"); }); // Output: Alice John Bob Eva Daniel
  • Now, sort the array in ascending order by default using the sort() method:
let names = ['Alice', 'John', 'Bob', 'Eva', 'Daniel']; names.sort(); document.write(names.join(", ") + "<br>"); // Output: Alice Bob Daniel Eva John

The array is now sorted in ascending order.

  • To sort the array in descending order, you can provide a custom comparison function:
let names = ['Alice', 'John', 'Bob', 'Eva', 'Daniel']; names.sort(comparisonFunction); function comparisonFunction(name1, name2) { if (name1 > name2) { return -1; } else if (name1 < name2) { return 1; } else { return 0; } } names.forEach(item => { document.write(item + "<br>"); }); // Output: John Eva Daniel Bob Alice

In the comparison function:

  • If it returns -1, name1 is placed before name2.
  • If it returns 1, name1 is placed after name2.
  • If it returns 0, name1 and name2 remain unchanged relative to each other.

By using this custom function, the array is sorted in descending order.