JavaScript Array sort() Method

 

Definition and Usage

The sort() sorts the elements of an array.

The sort() overwrites the original array.

The sort() sorts the elements as strings in alphabetical and ascending order.

For Number 

Sort Compare Function

Sorting alphabetically works well for strings ("Apple" comes before "Banana").

But, sorting numbers can produce incorrect results.

"25" is bigger than "100", because "2" is bigger than "1".

You can fix this by providing a "compare function" (See examples below)


<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>

  <script>
    const fruits = ["Banana", "Orange", "Apple", "Mango"];

    console.log(fruits.sort());


    const myNumber = [23,45,12,60,100];
    console.log(myNumber.sort());
   
  </script>

</body>

</html>

Comments

Popular posts from this blog

Javascript Array Concat and Join Method

JavaScript While Loop

JavaScript pop() Method