JavaScript Arrays Sorting

The JavaScript has a method sort() for sorting array elements in ascending order, i.e. the sorting will result into lowest to highest. For alphabetic values, the sorting will be according to the alphabetical series, the alphabet which comes first in the alphabetical series will be sorted first. Same for the numbers series, the lowest number will be sorted first and then the number bigger than the previous one and so on.

If both numbers and alphabets are present in the values then, first the alphabets will get sorted and then the numbers, like, Code, 15, Html, 20, 65 will be sorted as Code, Html, 15, 20, 65.


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> JavaScript Array Sorting </title>
</head>
<body>
<script>
var Smartphone = ["Google Pixel","Xiaomi"," Sony","Samsung"," Asus"];
document.write("Array Befor Short : " + Smartphone + "<br>");
var sorted = Smartphone.sort();
document.write("Array After Short : " + sorted);
</script>
</body>
</html>

Output

JavaScript Array Sorting

Array Reverse

The reverse() method is used to reverse the order of the elements of an array i.e. the first array element becomes the last, and the last array element becomes the first. Here, the sorting is not based on the ascending or descending orderering of the elements. Whatever the order of element is, reverse sorting will just reverse the order and nothing else.


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> JavaScript Array Reverse </title>
</head>
<body>
<script>
var Smartphones = [" Google Pixel ", " OnePlus ", " Samsung ", " Sony ", " Asus "];
document.write("Array Before Reverse : " + Smartphones + "<br>");
var reversed = Smartphones.reverse();
document.write("Array After Reverse : " + reversed);
</script>
</body>
</html>

Output

JavaScript Array Reverse





Become a Patron!

Note: If the updated content is not visible to you please refresh the cookies by pressing CTRL + Shift + R.