JavaScript Array Sort

The sort() method in JavaScript is sorting the elements in an array and will return the sorted array. The default sort order is according to string Unicode code points.


Array.sort()

Let's sort some animals

JS JavaScript - Array.sort()

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
    <body>
    <h1>Sort</h1>
    <p>Try to sort some nice animals</p>
    <button onclick="myFunction()">Sort The Animals</button>
    
    <script> 
            var animals = ["dog", "cat", "bird", "elephant"];
    
            function myFunction() {
                animals.sort();
                alert(animals); 
            }
    
    </script>
    </body>
</html>

Array.Reverse()

To reverse() the order of the elements in an array the reverse() method will do the job for you. The method will return an array where the elements are sorted in descending order

JS JavaScript - Array.Reverse()

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">

    <body>
    <h1>Reverse</h1>
    <p>Try to reverse</p>
    
    <button onclick="reverseSort()">Reverse the order of the elements in the array</button>
    
    <script>
        var animals = ["bird", "dog", "horse", "cat"];
        
        function reverseSort() {
            // Start with the sorting
            animals.sort();
            alert(animals);
            
            // Do the reverse
            animals.reverse();
            
            alert(animals);            
        }
    </script>
    </body>
<html>

Sort numeric values

The function sort() is by default sorting values as strings. Sorting numbers as strings might cause errors. By using the compare function this can be solved.

JS JavaScript - Sort numeric values

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
    <body>
    <h1>Sort numerics</h1>
    <p>Sort numeric values.</p>
    
    <button onclick="sortNumericValues()">Test sorting numeric values</button>
    
    <script>
        var temp = [40, 100, 1, 5, 25, 10];  
        
        function sortNumericValues() {        
            temp.sort(function(a, b){return a - b});
            
            document.getElementById("resultElement").innerHTML = temp;
        }
    </script>
    <p id="resultElement"></p>
    </body>
</html>

Lowest value in an array

If you wish to find the lowest or highest value you can get that by first sorting the array and then use the index value to get either the lowest or the highest.

JS JavaScript - Lowest value in an array

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
    <body>
    <button onclick="getLowestValue()">Click me to get the lowest value</button>
    
    <script>
        var temp = [2, 4, 1, 9, 33, 22, 39];

        function getLowestValue() {
            temp.sort(function(a, b){return a-b});

            alert(temp[0]); // Get the lowest by using index 0.
        }
    </script>

    </body>
</html>

Learn more about JavaScript Array Iteration

Highest value in an array

JS JavaScript - Highest value in an array

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
    <body>
    <button onclick="getHighestValue()">Click me to get the highest value</button>
    
    <script>
        var temp = [2, 4, 1, 9, 33, 22, 39];

        function getHighestValue() {
            temp.sort(function(a, b){return a-b});

            alert(temp[temp.length - 1]);
        }
    </script>

    </body>
</html>

When we are sorting an array in descending order we use (return b - a) and when we are sorting in ascending order we use (return a - b)


Sort objects

Even objects in JavaScript can be sorted.

JS JavaScript - Sort objects

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
    <body>
    <h1>Sort objects</h1>
    
    <button onclick="startSorting()">Test sorting numeric values</button>
    
    <script>
        var kids = [
                {name:"Dick", age:9},
                {name:"Sandy", age:5},
                {name:"Peter", age:2}
            ]
        
        function startSorting() {
            kids.sort(function(a, b){return a.age - b.age});
            
            showKids();
        }
        
        function showKids() {
            alert(
            kids[0].name + " " + kids[0].age + " : " +
            kids[1].name + " " + kids[1].age + " : " +
            kids[2].name + " " + kids[2].age);        
        }
    </script>
    </body>
</html>

Learn more about JavaScript Objects and Arrays
BACK TO TOP






Check this out

JS JavaScript: Array Sort

The sort() method in JavaScript is sorting the elements in an array and will return the sorted array. The default sort order is according to string Unicode code points.

JS JavaScript: Debugging

Searching for bugs and fixing them is called code debugging.

The bugs might be difficult to diagnose and therefore it is important to have a good approach to find and fix the bugs effectively.

JS JavaScript: Scope

Scope determines if variables are accessible (visible).

A scope in JavaScript defines what variables you have access to. There are two kinds of scope – global scope and local scope.

Function scope and block scope are local scope - variables declared inside a function or a bl....

JS JavaScript: Random

JavaScript have a Random number function. The method can generate a number in a specific range. The number can not be reasonably be predicted.


BACK TO TOP

JavaScript is one of the 3 core language technologies of the World Wide Web that all web developers must learn:

1.      HTML to define the content of web pages.

2.      CSS to specify the layout of web pages.

3.      JavaScript to program the behavior of web pages.

JavaScript is a scripting or programming language that allows you to implement complex things on web pages. Every time a web page does more than just sit there and display static information for you to look at, displaying timely content updates, interactive maps, animated 2D/3D graphics, scrolling video jukeboxes, etc. − you can bet that JavaScript is probably involved.


The benefits of using JavaScript are:

1.      You can validate user input before sending the page off to the server. This saves server traffic, which means less load on your server.

2.      Immediate feedback to the visitors − They don't have to wait for a page reload to see if they have forgotten to enter something.

3.      Increased interactivity − You can create interfaces that react when the user hovers over them with a mouse or activates them via the keyboard.

4.      Richer interfaces − You can use JavaScript to include such items as drag-and-drop components and sliders to give a Rich Interface to your site visitors.


BACK TO TOP

Need more Honney

NDC Conferences

The NDC Conferences (Norwegian Developers Conference) are one of the world`s largest independent software conferences for .NET & Agile development. The conference covers everything you need to know within software development. The conferences are held each year in many places such as Oslo, Copenhagen, London, Sydney and Minnesota.

Update Conference Prague

Update Conference Prague is the biggest developer conference in the Czech Republic. The conference is offering sessions delivered by the top experts from all around the world. Their goal is to inspire the attendees and enrich their knowledge.

Troy Hunt

Learn about Web Security from Troy Hunt. He is a really engaged speaker that frequently give talks on conferences around the world. Troy is a Microsoft MVP and you can even learn from him on some great courses on Pluralsight.

W3Schools

W3Schools.com is a great education Web Site for learning web technologies. On W3Schools you may find well organized basic to advanced tutorials and references.

Scott Hanselman

Learn about Web Technologies and new trends from Scott Hanselman. Scott Hanselman is an author of developer books and he is an engaged speaker that usually talks about the Microsoft stack. You may meet Scott on conferences around the world.

Developer Week

DeveloperWeek is one of the world’s largest developer conferences. Developer Week focus on new dev technologies, the conference have talks and workshops for newbies and experienced audience. You can attend on a Developer Week conference different places in Nothern America.


BACK TO TOP

Honneybag blog



Learn JavaScript Debugging

Searching for bugs and fixing them is called code debugging. The bugs might be difficult to diagnose and therefore it is important to have a good approach to find and fix the bugs effectively. Bugs in the code might be syntax errors or logical errors. Sometimes nothing happens when the code contains bugs and there is few indications where to search. Modern web browser includes a powerful suite of developer tools. The tools do a range of things...

Explore JavaScript Arrays

Arrays are frequently used by developers. Programming languages can have slightly different implementation of arrays. An array is an object that can store a collection of items. You may say it`s a special variable that can have more than one value. The array holds many values under a single name, and you may access the values by referring to an index number. The easiest way to create....

Ultimate Guide to HTML Colors

It is essential to give the user a good user experience. There are many things you should focus on, one of them is how you use colors on your website. We don't have to struggle with black and white TVs anymore. Users expect more and more and we can apply colors to everything we want. Texts, borders, backgrounds, shadows – in HTML they all can have whatever color you decide....

Wanna be a sheep? Check out the most popular subjects
HONNEYBAG BLOG
HONNEYBAGBLOG INSPIRE-AND-BE-INSPIRED
HTML FORMATTING
JAVASCRIPT ESSENTIALS
HONNEYBAGBLOG EXPLORE-JAVASCRIPT-ARRAYS
Wanna be a little different? Check out the less popular subjects
HONNEYBAG BLOGER
HTML INTRODUCTION
HTML INTRODUCTION
HTML ESSENTIALS
HTML ESSENTIALSWE
BACK TO TOP