Javascript Array Sort

Array sorting allows us to sort elements of an array in place. Besides returning the sorted array, the sort() method changes the positions of the elements in the original array.


Sorting an array

This method sorts an array alphabetically.

Input:-
 <script>  
     var frontend = ['HTML', 'CSS','Javascript'];
     frontend.sort();
     document.write(frontend + "<br>"); 
</script>

Output:-


Reversing an array

This reverse() method reverses the elements in an array. We can use it to sort an array in descending order.

Input:-
 <script>  
     var frontend = ['HTML', 'CSS','Javascript'];
     frontend.sort();
     frontend.reverse();
     document.write(frontend + "<br>"); 
</script>

Output:-


Sorting an array of objects by a numeric property

This method contains an array with object in it and then we compare those object number values with each other. Suppose an array with name employees and each object contains three properties: name, age and designation.

Input:-
 <script>  
    let employees = [
            {name: 'John', age: 21, designation: "Frontend Developer"},
            {name: 'David', age: 25, designation: "Backend Developer"},
            {name: 'Ana', age: 24, designation: "Graphic Designer"}
        ]; 
        employees.sort(function (x, y) {
            return x.age - y.age;
        });
        console.table(employees); 
</script>

Output:-


Sorting an array of objects by a string property

This method contains an array with object in it and then we compare those object string values with each other. Suppose an array with name employees and each object contains three properties: name, age and designation.

Input:-
 <script>  
        let employees = [
            {name: 'John', age: 21, designation: "Frontend Developer"},
            {name: 'David', age: 25, designation: "Backend Developer"},
            {name: 'Ana', age: 24, designation: "Graphic Designer"}
        ]; 
        employees.sort(function (x, y) {
            let a = x.name.toUpperCase(),
            b = y.name.toUpperCase();
            return a == b ? 0 : a > b ? 1 : -1;
        });

        console.table(employees); 
</script>

Output:-