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 How to check if radio button is checked or not using JavaScript? #2 How to add Read More Read Less Button using JavaScript? #3 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #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

#Dec 4 What is Etrieve Flow? #Dec 2 The unique operator($) in Envision Basic #Nov 25 Steps to Install Microsoft SQL Server on a MacOS #Nov 11 What is DevOps? #Nov 10 The * arithmetic operator in Envision Basic #Nov 10 What are Big Data Clusters in SQL Server?
You might also like these
transform-origin Property in CSSCSSSolution for “Yarn build: Failed because of a stylelint error”WordPressPHP Variables ScopePHPSorting Arrays in JavaScriptJavaScriptHow does Binding work in JavaScript?JavaScriptWordPress: How to display slider repeater fields in ACF?WordPressWhat is the best way to add JavaScript Code into HTML?HTMLHow to add multiple Columns in CSS like Bootstrap?CSSSolution for Xcode 11 Command PhaseScriptExecution failed with a nonzero exit code errorMiscellaneousHow Routing works in Angular?Angularsubstring() Method in JavaScriptJavaScriptHow to position an image on top of another image using CSS?CSS