JavaScript Code

JavaScript Array sort()


sort() – Sort Elements of Array

array.sort()
array.sort(compareFunction)
  • array is an array which should be sorted
  • sort is the array method name
  • compareFunction is a function that takes two parameters and returns a value

sort() method sorts the elements of the given array in ascending order. if compareFunction is provided, then the elements of the array are sorted based on the values returned by the compareFunction for each element of the array

to sort an array in descending order, reverse the array after sorting

sort() method modifies the original array

Examples

1. sort array of numbers in ascending order

let numbers = [5, 1, 7, 3, 2, 0];
numbers.sort();
console.log(numbers);

2. sort array of strings lexicographically in ascending order

let fruits = ['cherry', 'apple', 'banana'];
fruits.sort();
console.log(fruits);

3. sort array of strings based on length, in ascending order

function stringLength(str1, str2) {
    return str1.length - str2.length;
}

let names = ['Anita', 'Amy', 'America', 'Alba'];
names.sort(stringLength);
console.log(names);

4. sort array in descending order

let numbers = [5, 1, 7, 3, 2, 0];
numbers.sort();
numbers.reverse();
console.log(numbers);

Copyright @2022