sorting array in JavaScript

Hi All, I'm going to explain to sorting array in JavaScript.

Today's, I have a requirement to sorting array using JavaScript.

JavaScript have to Array.sort() method is default ascending order.

var empArray = ['x', 'a', 'z', ‘b’];
empArray.sort();

//Output: a, b, x and z.

These Code samples are working on mostly all browsers (IE, Mozilla, and Firefox etc.)

In the 1st step, Code Sample for JavaScript sorting Array objects

<script type="text/javascript" lang="ja">
     //Employee array collections.
    var employeeArray = [
        { empName: "Anil", empEmail: "anil.s@dotnetsql.in", empAge: 29 },
        { empName: "Sunil", empEmail: "sunil.s@dotnetsql.in", empAge: 22 },
        { empName: "Sushil", empEmail: "sushil.s@dotnetsql.in", empAge: 19 },
        { empName: "Reena", empEmail: "reena.s@dotnetsql.in", empAge: 23 },
        { empName: "Tinko", empEmail: "tinko.s@dotnetsql.in", empAge: 20 }
    ];

    //Method : sorting by ascending order by Email
    function orderByEmpEmailAscending(p, q) {
        if (p.empEmail == q.empEmail) {
            return 0;
        } else if (p.empEmail > q.empEmail) {
            return 1;
        }
        return -1;
    }
    //Method : sorting by ascending order by Age
    function orderByEmpAgeAscending(p, q) {
        return p.empAge - q.empAge;
}

    //Used to array.sort() method.
    employeeArray.sort(orderByEmpEmailAscending);
    employeeArray.sort(orderByEmpAgeAscending);
   
</script>



ANIL SINGH

Hey! I'm Anil Singh. I author this blog. I'm Active Blogger, Programmer. I love learning new technologies, programming, blogging and participating the forum discussions more...
My Blogs - http://www.code-sample.com and http://www.code-sample.xyz
My Books - Buy Books Online at Best Prices

You Might Also Like
Post a Comment
www.code-sample.com/. Powered by Blogger.