Skip to content

Instantly share code, notes, and snippets.

@geekelo
Created August 27, 2023 04:02
Show Gist options
  • Save geekelo/fcd9c8d79507b459fb5bfd657399e8f4 to your computer and use it in GitHub Desktop.
Save geekelo/fcd9c8d79507b459fb5bfd657399e8f4 to your computer and use it in GitHub Desktop.
Sorting in JavaScript

To sort an array in JavaScript, you can use the sort() method. The sort() method sorts the elements of an array in place and returns the sorted array. By default, it sorts the elements as strings, which might not be suitable for numeric or custom sorting. You can pass a comparison function to the sort() method to customize the sorting behavior.

Here's the basic syntax for using the sort() method:

array.sort([compareFunction])

If you want to sort an array of numbers, you can provide a custom comparison function to achieve numeric sorting:

function compareNumbers(a, b) {
  return a - b;
}

let numbers = [3, 1, 4, 1, 5, 9, 2, 6];
numbers.sort(compareNumbers);

console.log(numbers); // Output: [1, 1, 2, 3, 4, 5, 6, 9]

For sorting strings in a case-insensitive manner:

function compareStringsCaseInsensitive(a, b) {
  return a.toLowerCase().localeCompare(b.toLowerCase());
}

let strings = ["apple", "Banana", "Orange", "banana", "cherry"];
strings.sort(compareStringsCaseInsensitive);

console.log(strings); // Output: ["apple", "banana", "Banana", "cherry", "Orange"]

Remember that the sort() method modifies the original array in place. If you want to keep the original array unchanged, you should make a copy of it before sorting.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment