EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

JavaScript Array Sort

By Priya PedamkarPriya Pedamkar

Home » Software Development » Software Development Tutorials » JavaScript Tutorial » JavaScript Array Sort

JavaScript Array Sort

Introduction to JavaScript Array Sort

Sorting means arrange items in a specific order. Array Sorting means to arrange the elements in either ascending or descending order. Array sorting can be performed with strings and numbers.

Real-time Example: When we want to sort out Amazon products either by based on price or brand company or product name etc. It is very difficult to iterate the items with for loop or while loop because execution time is more. So, instead of that, we can use predefined methods provided by JavaScript. That is sort(), reverse() etc.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

How does Array Sort work in JavaScript?

  • Sorting the strings sort() predefined function is preferable.

Syntax:

Array[“string1”,”string2”,”string3”].sort(); //ascending order by default

  • By default sort() function sorting is in ascending order.
  • If we want descending order, apply reverse() function on sort() function result.

Syntax:

var ascend=Array[“string1”,”string2”,”string3”].sort();
ascend.reverse(); //descending order

  • When sorting the numbers sort() function is not recommended because it works accurately with strings.
  • Sorting numbers compare function is recommendable for accurate results.

Syntax:

Array[number1, number2,number3].sort(function(x,y){ return x-y}); // ascending order

  • Above sorting is in ascending order, if we want descending order by changing return a-b as return b-a.

Syntax:

Array[number1, number2,number3].sort(function(x,y){ return y-x}); // descending order

  • Sort(function(x,y)) every time takes 2 values compares
Note: function(1st,2nd), function(2nd ,3rd ), function(3rd t,4th ), function(4th ,5th )…..until array emptied.
  • If return x-y gives negative means y is greater than x so, x comes before y.
  • If return x-y gives positive means x is greater than y so, y comes before x.
  • If return x-y gives 0 means x and y are equal so, values not swapped.
  • This process similar for return y-x, descending order as well.
  • This process repeats until array emptied.

Examples of JavaScript Array Sort

Given below are the examples mentioned :

Example #1

Sorting Strings in ascending order.

Code:

<!DOCTYPE html>
<html>
<body>
<font color="green">
<h1 align="center">Sorting Strings Ascending Order</h1>
</font>
<script>
function getStringAscendOrder() {
var alphabets=["Q","z","q","a","m","M","I","i","c","U","u","Z","d","A","C","D"];
var alphabetsSort=alphabets.sort();
document.write(alphabetsSort);
}
getStringAscendOrder();
</script>
</body>
</html>

Output:

JavaScript Array Sort 1

Explanation:

  • In the above code, we have clearly seen the sorting of the array is in ascending order. But in JavaScript Uppercase letters are first preceded by lower case letters.
  • So, in the output, All Uppercase letters come first and lower-case letters next in the ascending order by applying sort() function on an array.

Example #2

Sorting Strings in descending order.

Code:

<!DOCTYPE html>
<html>
<body>
<font color="green">
<h1 align="center">Sorting Strings Descending Order</h1>
</font>
<script>
function getStringDescendOrder() {
var alphabets=["Q","z","q","a","m","M","I","i","c","U","u","Z","d","A","C","D"];
var alphabetsSort=alphabets.sort();
document.write(alphabetsSort.reverse());
}
getStringDescendOrder();
</script>
</body>
</html>

Output:

sorting string in descending order

Explanation:

  • Get descending elements from an array first apply sort() function on array.
  • On resultant array apply reverse() function then we will get exactly opposite output against ascending order.

Example #3

Why sort() function not preferable over numbers?

Numbers with direct sort() function.

Code:

<!DOCTYPE html>
<html>
<body>
<font color="green">
<h1 align="center"> Sort() function numbers</h1>
</font>
<script>
function getNumbersSort() {
var numbers=[1,-5,0,10,20,9];
document.write(numbers.sort());
}
getNumbersSort ();
</script>
</body>
</html>

Output:

numbers with direct sort functions

Explanation:

  • In the above output, you can clearly see 9 is not greater than 20 even arranged after 20.
  • It clearly proved the direct sort() function is not recommendable on numbers.

Example #4

Sorting numbers in ascending order.

Code:

<!DOCTYPE html>
<html>
<body>
<font color="green">
<h1 align="center">Sorting Numbers Ascending Order</h1>
</font>
<script>
function getNumberAscendOrder () {
var numbers=[121,52,47,69,78,-21,0,-52,55,78,-5];
var numbersSort=numbers.sort(function(x,y)
{
return x-y
});
document.write(numbersSort);
}
getNumberAscendOrder();
</script>
</body>
</html>

Popular Course in this category
JavaScript Training Program (39 Courses, 23 Projects, 4 Quizzes)39 Online Courses | 23 Hands-on Projects | 225+ Hours | Verifiable Certificate of Completion | Lifetime Access | 4 Quizzes with Solutions
4.5 (6,106 ratings)
Course Price

View Course

Related Courses
Angular JS Training Program (9 Courses, 7 Projects)Vue JS Training (1 Courses, 3 Project)

Output:

javascript array sort 4

Explanation:

  • In the above code numbers array passed to compare function inside sort() function.
  • At a time, the function takes just 2 values and compares.
  • Here returns resultant is x-y.
  • If the result is negative y comes before x.
  • If the result is positive x comes before y.
  • If the result is 0 values not swapped because values are the same.
  • This pattern repeats until array becomes emptied.
  • 121-52= positive
  • 52,121
  • 52,121,47
  • 121-47=positive
  • 52,47,121
  • 52,47,121
  • 52-47=positive
  • 47,52,121
  • 47,52,121,69
  • 121-69=positive
  • 47,52,69,121

Example #5

Sorting numbers in descending order.

Code:

<!DOCTYPE html>
<html>
<body>
<font color="green">
<h1 align="center">Sorting Numbers Descending Order</h1>
</font>
<script>
function getNumberDescendOrder() {
var numbers=[121,52,47,69,78,-21,0,-52,55,78,-5];
var numbersSort=numbers.sort(function(x,y)
{
return y-x
});
document.write(numbersSort);
}
getNumberDescendOrder ();
</script>
</body>
</html>

Output:

javascript array sort 5

Explanation:

  • In the above code numbers array passed to compare function inside sort() function.
  • At a time, the function takes just 2 values and compares.
  • Here returns resultant is y-x.
  • If the result is negative x comes before y.
  • If the result is positive y comes before x.
  • If the result is 0 values not swapped because values are the same.
  • This pattern repeats until the array becomes empty.
  • The output is exactly the opposite of ascending output.

If we want to get maximum value or minimum value from an array. No need to sort the entire array, we can get it by predefined functions Math.max() and Math.min().

Syntax:

Math.max(…array);
Math.min(…array);

Note: Must include 3 dots(…) before an array in the max or min function.

Example #6

Array Maximum and Minimum value.

Code:

<!DOCTYPE html>
<html>
<body>
<font color="green">
<h1 align="center">Maximum and Minimum values from an array </h1>
</font>
<script>
function getMaxAndMinValue() {
var numbers=[121,52,47,69,78,-21,0,-52,55,78,-5];
document.write("Maximum value from "+numbers+" array is =>"+Math.max(...numbers)+"<br>");
document.write("Minimum value from "+numbers+" array is =>"+Math.min(...numbers));
}
getMaxAndMinValue();
</script>
</body>
</html>

Output:

javascript array sort 6JPG

Explanation:

  • To get maximum value from an array just apply max() function to a given array.
  • To get the minimum value from an array just apply min() function to a given array.
  • After applying these 2 functions on the array result for maximum is 121 and the minimum is -52.

Conclusion

Sorting the string array used sort function directly whereas sorting numbers used compare function with sort function. Uppercase letters are first preferable in a string array. Sorting numbers based on the returned value of negative, positive and zero resultant.

Recommended Articles

This is a guide to JavaScript Array Sort. Here we discuss the introduction, how does array sort work in JavaScript? and examples. You may also have a look at the following articles to learn more –

  1. Multi-Dimensional Array in JavaScript
  2. Javascript void
  3. JavaScript prompt
  4. JavaScript Iterate Array

JavaScript Training Program (39 Courses, 23 Projects)

39 Online Courses

23 Hands-on Projects

225+ Hours

Verifiable Certificate of Completion

Lifetime Access

4 Quizzes with Solutions

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
JavaScript Tutorial
  • Array
    • Arrays in JavaScript
    • 2D Arrays in JavaScript
    • Multi-Dimensional Array in JavaScript
    • Associative Array in JavaScript
    • JavaScript Declare Array
    • Arrays Methods in JavaScript
    • JavaScript Loop Array
    • String Array in JavaScript
    • JavaScript Get Array Length
    • JavaScript Merge Arrays
    • JavaScript Array Sort
    • JavaScript Array Push
    • JavaScript Iterate Array
    • JavaScript Empty Array
    • JavaScript Array Concat
    • Dynamic Array in JavaScript
    • JavaScript subarray()
    • JavaScript Array Filter
    • JavaScript Nested Array
    • JavaScript Flatten Array
    • JavaScript Array map()
    • JavaScript Array includes()
    • JavaScript Array Contain
    • JavaScript Array Slice
    • JavaScript Copy Array
    • Javascript Sum Array
    • JavaScript reverse Array
    • JSON Parse Array
  • Basic
    • Introduction To JavaScript
    • What is JavaScript
    • What Javascript Can Do
    • Uses of JavaScript
    • How JavaScript Works
    • Is Javascript Case Sensitive
    • Is Javascript Object Oriented
    • Features of JavaScript
    • Careers in JavaScript
    • How to Install JavaScript
    • Best Javascript Frameworks
    • JavaScript MVC Frameworks
    • JavaScript Tools
    • What is JSON
    • What is Redux
    • What is ES6
    • Uses of React JS
    • How Analytics.JS Works
    • JavaScript Compilers
    • Java and JavaScript
    • JavaScript Literals
    • Variables in JavaScript
    • JavaScript Global Variable
    • JavaScript Keywords
    • String in JavaScript
    • Pointers in JavaScript
    • Primitive Data Types in JavaScript
    • JavaScript console log
    • Object in JavaScript
    • JavaScript Enum
    • Arithmetic in JavaScript
    • Assignment Operator in JavaScript
    • JavaScript Modules
    • Cheat Sheet JavaScript
    • NPM Alternatives
  • Objects
    • JavaScript Objects
    • JavaScript History Object
    • JavaScript Object Notation
    • JavaScript Map Object
    • JavaScript Date Object
    • JavaScript Window Object
    • JavaScript Object Constructors
    • JavaScript Clone Object
    • JavaScript Object.assign()
    • JavaScript object.is()
    • JavaScript Object to JSON
  • Operators
    • Arithmetic Operators in JavaScript
    • JavaScript Assignment Operators
    • Logical Operators in JavaScript
    • Comparison Operators in JavaScript
    • Bitwise Operators in JavaScript
    • Ternary Operator JavaScript
    • Boolean Operators in JavaScript
    • JavaScript?Modulo
    • JavaScript Boolean()
    • Unary Operators in JavaScript
    • JavaScript Number
    • JavaScript Floating
    • JS Operator Precedence
  • Control statements
    • Control Statement in JavaScript
    • Conditional Statements in JavaScript
    • Break Statement in JavaScript
    • Continue in JavaScript
    • Switch Statement in JavaScript
    • Case Statement in JavaScript
    • JavaScript if Statement
    • Nested if in JavaScript
    • JavaScript elseIf
  • Loops
    • For Loop in JavaScript
    • While Loop in JavaScript
    • Do While Loop in JavaScript
    • Nested Loop in JavaScript
  • Sorting
    • Sorting Algorithms in JavaScript
    • Insertion Sort in JavaScript
    • Merge Sort in JavaScript
    • Quick Sort in JavaScript
    • Bubble Sort in JavaScript
    • pop() in JavaScript
    • push() in JavaScript
    • Sort string in JavaScript
  • Functions
    • JavaScript String Functions
    • JavaScript String Length
    • JavaScript split String
    • JavaScript Math Functions
    • Recursive Function in JavaScript
    • Regular Expressions in JavaScript
    • JavaScript Arrow Function
    • JavaScript Date Function
    • Match Function in Javascript
    • Replace Function in JavaScript
    • JavaScript Call Function
    • JavaScript Pass By Value
    • split() Function in JavaScript
    • reduce() Function JavaScript
    • JavaScript String replace
    • JavaScript Compare Strings
    • JavaScript Sleep
    • JavaScript toLowercase()
    • JavaScript String to Float
    • JavaScript String to Number
    • JavaScript String to int
    • JavaScript Object to String
    • JavaScript Convert to JSON
    • JavaScript Append
    • Javascript Array to String
    • Javascript Nested Functions
    • Set in JavaScript
    • Vectors in JavaScript
    • Javascript Anonymous Function
    • sign() in JavaScript
    • isNaN() JavaScript
    • Slice() Method in JavaScript
    • Javascript void
    • endsWith() in JavaScript
    • trim() Function in JavaScript
    • JavaScript typeof
    • JavaScript indexOf()
    • JavaScript encodeURI()
    • JavaScript Random
    • Ceil() in JavaScript
    • JavaScript tofixed
    • JavaScript hash()
    • JavaScript MD5
    • JavaScript search
    • JavaScript z-index
    • JavaScript Absolute Value
    • JavaScript Closure
    • Javascript Prototype
    • JavaScript Date parse
    • JavaScript DatePicker
    • JavaScript Parse String
    • JavaScript undefined
    • JavaScript FileReader
    • JavaScript Style visibility
    • JavaScript sleep Function
    • JavaScript forEach()
    • JavaScript keys()
    • JavaScript keycodes
    • JavaScript find() 
    • JavaScript values()
    • JavaScript Counter
    • JavaScript Countdown
    • JavaScript instanceof
    • JavaScript Delay
    • JavaScript Default Value
    • JavaScript concat String
    • JavaScript Document Object Model
    • Unshift JavaScript
    • JavaScript Callback Function
    • JavaScript hasOwnProperty()
    • JavaScript UUID
    • JSON Parser
    • JSON Array of Strings
    • Sublime Pretty JSON
    • JavaScript JSON to string
    • JavaScript Uppercase
    • JavaScript Namespace
    • JavaScript Range
    • JavaScript JSON
    • JavaScript exec()
    • JavaScript test()
    • JavaScript Self Invoking Functions
    • JSON Stringify Pretty
    • JavaScript findIndex()
    • JavaScript entries()
    • JavaScript join()
    • JavaScript lastIndexOf()
    • JavaScript every()
    • JavaScript getElementById()
    • JavaScript getElementsByName()
    • JavaScript getElementsByTagName()
    • JavaScript getElementsByClassName()
    • JavaScript Animation
    • JavaScript Minify
  • Events
    • JavaScript Events
    • JavaScript Event Handler
    • JavaScript Keyboard Events
    • JavaScript Mouse Events
    • JavaScript mousemove
    • JavaScript mousedown
    • JavaScript onchange
    • JavaScript onmouseout
    • JavaScript Onkeydown
    • JavaScript onsubmit
    • JavaScript Form Events
    • JavaScript Window Events
    • JavaScript Custom Events
    • JavaScript Alert
    • JavaScript Confirm
    • JavaScript onclick Alert
    • JavaScript Apply
    • JavaScript onblur
    • JavaScript onkeyup
    • JavaScript onfocus
  • Advanced
    • Constructor in JavaScript
    • Inheritance in JavaScript
    • Polymorphism in JavaScript
    • JavaScript Static Method
    • Navigator in JavaScript
    • Abstract Classes in JavaScript
    • keyword in JavaScript
    • Overriding in JavaScript
    • JavaScript Clear Console
    • JavaScript References
    • JavaScript list
    • JavaScript Grid
    • JavaScript innerText
    • Cookies in JavaScript
    • Delete Cookie in JS
    • Encapsulation in JavaScript
    • JavaScript Parent Node
    • JavaScript Parent
    • Javascript Remove Element
    • Errors in JavaScript
    • Forms in JavaScript
    • JavaScript Validator
    • JavaScript Form Validation
    • Email Validation in JavaScript
    • Hamburger Menu JavaScript
    • JavaScript Date Formats
    • JavaScript Number Format
    • JavaScript Debugger
    • JavaScript Stack
    • Queue in JavaScript
    • parseFloat in JavaScript
    • Javascript innerHTML
    • JavaScript setInterval
    • JavaScript Popup Box
    • JavaScript Message Box
    • Lightbox in JavaScript
    • Javascript Design Patterns
    • addEventListener JavaScript
    • Timer in JavaScript
    • JavaScript setTimeout
    • JavaScript clearTimeout()
    • JavaScript String Format
    • JavaScript Scroll to Top
    • JavaScript Function Declaration
    • JavaScript Function Arguments
    • Javascript Strict Mode
    • File Handling in JavaScript
    • JavaScript parseInt
    • JavaScript prompt
    • JavaScript Set Class
    • JavaScript Try Catch
    • Javascript Throw Exception
    • Finally in JavaScript
    • JavaScript Get Element by Class
    • JavaScript Obfuscator
    • Disable JavaScript
    • SetAttribute JavaScript
    • JavaScript Cursor
    • LinkedList in JavaScript
    • JavaScript WeakMap
    • JavaScript DOM
    • JavaScript defer
    • JavaScript Promise
    • Pagination in JavaScript
    • JavaScript Refresh Page
    • JSON.stringify JavaScript
    • JavaScript IIFE
    • JavaScript Fetch API
    • JavaScript Auto Complete
    • JavaScript Copy to Clipboard
    • JavaScript querySelector
    • JavaScript Graph
  • Programs
    • Patterns in JavaScript
    • Reverse in JavaScript
    • Palindrome in JavaScript
    • Factorial Program in JavaScript
    • Fibonacci Series In JavaScript
    • Square Root in JavaScript
    • Prime Number in JavaScript
    • Armstrong Number in JavaScript
    • Random Number Generator in JavaScript
    • Reverse String in JavaScript
    • JavaScript Random String
    • Functional Programming in JavaScript
  • Interview Questions
    • Javascript Interview Questions
    • JSON Interview Questions
    • JS Interview Questions

Related Courses

JavaScript Certification Training

Angular JS Certification Training

Vue JS Training

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - JavaScript Training Program (39 Courses, 23 Projects) Learn More