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' ]



Most Read

#1 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
Avoid using new Array() in JavaScriptJavaScriptThe Sort and Compare Functions in JavaScriptJavaScriptHow to include CSS and JavaScript files in your WordPress plugin?WordPressCasting in PostgreSQLPostgresSteps to Secure a VPNMiscellaneousWordPress: How to setup and get values from an ACF options page?WordPressHow to verify your domain in Google Console with a TXT record?MiscellaneousSubquery in PostgresPostgresHow to create two segues with two UIButtons on a single page (Swift 5.0)?SwiftWhat is HTMLUnknownElement?HTMLWhat are keys in React?ReactWordPress: How to create a folder if it doesn’t already exist?WordPress