YogeshChauhan . com

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


dreamhost

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 uninstall Cocoapods from the Mac OS? #4 How to add Read More Read Less Button using JavaScript? #5 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

May 5 Use inline if to make a shorter conditional syntax in React May 4 What is Conditional Rendering in React? May 3 How does @extend rule work in SCSS (Sass)? May 2 How different is Handling Events in React vs HTML DOM? May 2 How to create bouncing balls using HTML canvas and JavaScript? Apr 30 HTML canvas methods

You might also like these

All different methods for accessing elements in the DOM using JavaScriptJavaScriptWordPress: How to display slider repeater fields in ACF?WordPressSelector Lists and Combinators in SCSS (Sass)SCSSHow to show widgets on the Appearance tab in WordPress?WordPressHow to Secure Web or Mobile Browsers?MiscHow to add Date and Time picker in HTML and get the values using JavaScript?HTMLHow to scroll contents of a an element vertically using JavaScript?JavaScript2 Ways we can create an Array in JavaScriptJavaScriptUNION and UNION ALL in PostgresPostgresbin2hex() and chr() String Functions in PHPPHPHow to import MySQL small sample database into phpMySQL?SQL/MySQLHow to convert an HTML radio buttons into a toggle switch using CSS?CSS