How to use JavaScript Array sort()

Program to use JavaScript Array sort() method


let a = [1,3,5,2,4];
let b = a.sort();

console.log(b);

Output


[ 1, 2, 3, 4, 5 ]

Steps Description

  1. Declare two variable a and b
  2. Initialize two variable with value of array a = [1,3,5,2,4] and b = a.sort()
  3. Array sort() method sorts the array from descending to ascending order.
  4. The value of b variable is displayed with the help of console.log inbuilt function

Program to use JavaScript Array sort() method


let c = [ 'Cat', 'Dog', 'Tiger', 'Lion', 'Elephant' ];
let d = c.sort();

console.log(d);

Output


[ 'Cat', 'Dog', 'Elephant', 'Lion', 'Tiger' ]

Steps Description

  1. Declare two variable c and d
  2. Initialize two variable with value of array c = [ 'Cat', 'Dog', 'Tiger', 'Lion', 'Elephant' ] and d = c.sort()
  3. Array sort() method sorts the array from descending to ascending order.
  4. The value of d variable is displayed with the help of console.log inbuilt function