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 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

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
Reading Multiple Inputs in SwiftSwiftSocial Media Colors: LESS VariablesMiscellaneousIntroduction to components and templates Part 2: Templates and viewsAngularA Step by Step Guide to Make RSS in XML For Any Website or Blog For FreeMiscellaneousHow to create HTML elements with ID and class using JavaScript?HTMLIs there a way to do a FULL OUTER JOIN in MySQL?SQL/MySQLHow to reprocess failed items in Etrieve Flow?MiscellaneousOptional arguments, Default parameters and REST parameters in JavaScriptJavaScriptCONCAT and CONCAT_WS Functions in PostgresPostgresA simple example on grid ‘auto-fill’ vs ‘auto-fit’CSSHow to add AppRoutingModule in Angular application using command line?Angular2 Ways We Can Write Multiple Line Commands in PHPPHP