Yogesh Chauhan's Blog

Sorting Arrays in JavaScript

in JavaScript on August 12, 2020

The sort() method

sorts an array alphabetically:

Example



var fruits = ["Banana", "Orange", "Apple", "Mango"];
console.log(fruits); 
// [ 'Banana', 'Orange', 'Apple', 'Mango' ]

console.log(fruits.sort());
// [ 'Apple', 'Banana', 'Mango', 'Orange' ]


The reverse() method

This one just reverses the array:



var fruits = ["Banana", "Orange", "Apple", "Mango"];
console.log(fruits);
// [ 'Banana', 'Orange', 'Apple', 'Mango' ]

console.log(fruits.reverse());
// [ 'Mango', 'Apple', 'Orange', 'Banana' ]


Order alphabetically in descending order



var fruits = ["Banana", "Orange", "Apple", "Mango"];
console.log(fruits);
// [ 'Banana', 'Orange', 'Apple', 'Mango' ]

console.log(fruits.sort());
// [ 'Apple', 'Banana', 'Mango', 'Orange' ]

console.log(fruits.reverse());
// [ 'Mango', 'Apple', 'Orange', 'Banana' ]



amazon

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS? #Aug 1 What is Zdog? #Aug 1 How to add before after image effect using pure CSS? #Jul 31 Add animation to your skills bar using CSS #Jul 31 Use SwiperJS to create mobile touch sliders fast
You might also like these
Safe Practice to add Links to cross-origin destinationUI/UXArray.from() Method in JavaScriptJavaScriptMySQL queries to get data rows from previous month as well as from last 30 daysSQL/MySQLclip and clip-path properties in CSSCSSAmpersand (Parent Selector) in SCSS (Sass)SCSSHow to use @supports rule in CSS?CSSThe Complete Basic Explanation of PHP SessionsPHPperspective property in CSSCSSbin2hex() and chr() String Functions in PHPPHPHow to display and animate image on scroll using JavaScript?JavaScriptHow to make a Custom Login Page in WordPress?WordPressThe Difference Between isNaN() Method And isNaN() Function In JavaScriptJavaScript