How to use JavaScript Array sort()

Array sort

Array sort() method

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

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

Array sort() method

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

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